﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RN.ERP.DAL;
using Newtonsoft.Json;
using RN.ERP.Entity.QD;
using RN.ERP.Entity;
using RN.ERP.BLL.Utilities;
using RN.ERP.DAL.DAL;
using Fly.Log;
using RN.ERP.Entity.ResultModels;
using RN.ERP;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using RN.ERP.BLL.QD.Utilities;

using User_Log = Fly.Log.User_Log;
using User_Log_Data = Fly.Log.User_Log_Data;
using Fly.FlyCommon;
using System.Data.Entity;

namespace RN.ERP.BLL.QD
{
    /// <summary>
    /// 人员管理
    /// </summary>
    public partial class PersonBLL : BasePersonBLL
    {
        #region dbContext
        private QD_Context qdcontext
        {
            get
            {
                return (QD_Context)base.baseContext;
            }
        }

        public PersonBLL()
        {
            base.baseContext = new QD_Context();
        }
        #endregion

        #region 私有方法
        private LogAndFlowHelper loghelper = new LogAndFlowHelper();

        /// <summary>
        /// 插入一条tb_flowcode记录
        /// </summary>
        /// <param name="objectid"></param>
        /// <param name="codetype"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        private bool AddFlowCode(string objectid, int codetype, string roleid, User_Log log = null)
        {
            var flowCode = qdcontext.FlowCodes.Where(f => f.ObjectId == objectid && f.CodeType == codetype).OrderByDescending(fo => fo.UpdateTime).FirstOrDefault();
            if (flowCode == null)
            {

                Entity.QD.Tb_FlowCode model = new Entity.QD.Tb_FlowCode();
                model.ObjectId = objectid;
                model.AreaCode = "02";
                model.CodeType = codetype;
                model.RoleId = roleid;
                model.FlowCode = FlowHelper.GetQdFlowCode(0, 0, false);
                model.UpdateTime = DateTime.Now;
                model.IsDel = false;
                if (log != null)
                {
                    model.UserId = log.IsrtUser;
                }
                return loghelper.AddFlowcode(model);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 修改人员（未被调用）
        /// </summary>
        /// <param name="currentCorp"></param>
        /// <param name="corp"></param>
        /// <returns></returns>
        private int ModifyManagerInternal(tb_Emp_Manager currentManager, tb_Emp_Manager manager)
        {
            if (manager != null)
            {

                currentManager.TypeFlag = manager.TypeFlag;
                if (currentManager.YaZhengCount != null)
                {
                    currentManager.YaZhengCount = manager.YaZhengCount;
                }
                if (manager.zgzcCode != null)
                {
                    currentManager.zgzcCode = manager.zgzcCode;
                }
                if (manager.ZhiWu != null)
                {
                    currentManager.ZhiWu = manager.ZhiWu;
                }
                if (manager.ArchiveCode != null)
                {
                    currentManager.ArchiveCode = manager.ArchiveCode;
                }
                if (manager.ArchiveCorp != null)
                {
                    currentManager.ArchiveCorp = manager.ArchiveCorp;
                }
                if (manager.ArchiveCorpLinkMan != null)
                {
                    currentManager.ArchiveCorpLinkMan = manager.ArchiveCorpLinkMan;
                }
                if (manager.ArchiveCorpTel != null)
                {
                    currentManager.ArchiveCorpTel = manager.ArchiveCorpTel;
                }
                if (manager.ArchiveRemark != null)
                {
                    currentManager.ArchiveRemark = manager.ArchiveRemark;
                }
                if (manager.AreaCode != null)
                {
                    currentManager.AreaCode = manager.AreaCode;
                }
                if (manager.AuthorGuid != null)
                {
                    currentManager.AuthorGuid = manager.AuthorGuid;
                }
                if (manager.bCanBid_0210 != null)
                {
                    currentManager.bCanBid_0210 = manager.bCanBid_0210;
                }
                if (manager.Birthday != null)
                {
                    currentManager.Birthday = manager.Birthday;
                }
                if (manager.BithdayMonth != null)
                {
                    currentManager.BithdayMonth = manager.BithdayMonth;
                }
                if (manager.BithdayYear != null)
                {
                    currentManager.BithdayYear = manager.BithdayYear;
                }
                if (manager.corpName != null)
                {
                    currentManager.corpName = manager.corpName;
                }
                if (manager.CreatDate != null)
                {
                    currentManager.CreatDate = manager.CreatDate;
                }
                if (manager.dogisZero != null)
                {
                    currentManager.dogisZero = manager.dogisZero;
                }
                if (manager.DoMajor != null)
                {
                    currentManager.DoMajor = manager.DoMajor;
                }
                if (manager.domajorint != null)
                {
                    currentManager.domajorint = manager.domajorint;
                }
                if (manager.Duty != null)
                {
                    currentManager.Duty = manager.Duty;
                }
                if (manager.DutyLevel != null)
                {
                    currentManager.DutyLevel = manager.DutyLevel;
                }
                if (manager.Education != null)
                {
                    currentManager.Education = manager.Education;
                }
                if (manager.EMail != null)
                {
                    currentManager.EMail = manager.EMail;
                }
                if (manager.EmployeeType != null)
                {
                    currentManager.EmployeeType = manager.EmployeeType;
                }
                if (manager.F_del_20101222 != null)
                {
                    currentManager.F_del_20101222 = manager.F_del_20101222;
                }
                if (manager.FlowCode != null)
                {
                    currentManager.FlowCode = manager.FlowCode;
                }
                if (manager.FlowCode_zjzx != null)
                {
                    currentManager.FlowCode_zjzx = manager.FlowCode_zjzx;
                }
                if (manager.FlowCode2 != null)
                {
                    currentManager.FlowCode2 = manager.FlowCode2;
                }
                if (manager.GraduatedSchool != null)
                {
                    currentManager.GraduatedSchool = manager.GraduatedSchool;
                }
                if (manager.IDCard != null)
                {
                    currentManager.IDCard = manager.IDCard;
                }
                if (manager.IDType != null)
                {
                    currentManager.IDType = manager.IDType;
                }
                currentManager.IfHaveCA = manager.IfHaveCA;
                if (manager.InsuranceNum != null)
                {
                    currentManager.InsuranceNum = manager.InsuranceNum;
                }
                if (manager.InsutanceCode != null)
                {
                    currentManager.InsutanceCode = manager.InsutanceCode;
                }
                if (manager.InsutanceCorp != null)
                {
                    currentManager.InsutanceCorp = manager.InsutanceCorp;
                }
                if (manager.InsutanceCorpLinkMan != null)
                {
                    currentManager.InsutanceCorpLinkMan = manager.InsutanceCorpLinkMan;
                }
                if (manager.InsutanceCorpTel != null)
                {
                    currentManager.InsutanceCorpTel = manager.InsutanceCorpTel;
                }
                if (manager.InsutanceRemark != null)
                {
                    currentManager.InsutanceRemark = manager.InsutanceRemark;
                }
                if (manager.IsDel != null)
                {
                    currentManager.IsDel = manager.IsDel;
                }
                if (manager.isFreeze != null)
                {
                    currentManager.isFreeze = manager.isFreeze;
                }
                if (manager.IsLeave != null)
                {
                    currentManager.IsLeave = manager.IsLeave;
                }
                if (manager.isShenBao != null)
                {
                    currentManager.isShenBao = manager.isShenBao;
                }
                if (manager.isZZEmp != null)
                {
                    currentManager.isZZEmp = manager.isZZEmp;
                }
                if (manager.MobileTel != null)
                {
                    currentManager.MobileTel = manager.MobileTel;
                }
                if (manager.MsgRoles != null)
                {
                    currentManager.MsgRoles = manager.MsgRoles;
                }
                if (manager.Name != null)
                {
                    currentManager.Name = manager.Name;
                }
                if (manager.oldid != null)
                {
                    currentManager.oldid = manager.oldid;
                }
                if (manager.OrginazationCode != null)
                {
                    currentManager.OrginazationCode = manager.OrginazationCode;
                }
                if (manager.PhotoFile != null)
                {
                    currentManager.PhotoFile = manager.PhotoFile;
                }
                if (manager.pwd != null)
                {
                    currentManager.pwd = manager.pwd;
                }
                if (manager.Remark != null)
                {
                    currentManager.Remark = manager.Remark;
                }
                if (manager.Sex != null)
                {
                    currentManager.Sex = manager.Sex;
                }
                if (manager.SpecialityID != null)
                {
                    currentManager.SpecialityID = manager.SpecialityID;
                }
                if (manager.SpecialityTxt != null)
                {
                    currentManager.SpecialityTxt = manager.SpecialityTxt;
                }
                if (manager.StartTime != null)
                {
                    currentManager.StartTime = manager.StartTime;
                }
                if (manager.tb_Emp_IsOuter != null)
                {
                    currentManager.tb_Emp_IsOuter = manager.tb_Emp_IsOuter;
                }
                if (manager.Tel != null)
                {
                    currentManager.Tel = manager.Tel;
                }
            }
            return qdcontext.SaveChanges();
        }

        /// <summary>
        /// 修改人员资质
        /// </summary>
        /// <param name="currentquality"></param>
        /// <param name="quality"></param>
        /// <returns></returns>
        private int ModityManagerQuality(Tb_Emp_TitleDetails currentquality, Tb_Emp_TitleDetails quality)
        {
            if (quality != null)
            {
                if (quality.bSendFlag != null)
                {
                    currentquality.bSendFlag = quality.bSendFlag;
                }
                if (quality.CertificateCode != null)
                {
                    currentquality.CertificateCode = quality.CertificateCode;
                }
                if (quality.CertificateLevel != null)
                {
                    currentquality.CertificateLevel = quality.CertificateLevel;
                }
                if (quality.CertificateName != null)
                {
                    currentquality.CertificateName = quality.CertificateName;
                }
                if (quality.CertificateSpecialty != null)
                {
                    currentquality.CertificateSpecialty = quality.CertificateSpecialty;
                }
                if (quality.ClassID != null)
                {
                    currentquality.ClassID = quality.ClassID;
                }
                if (quality.CLCode != null)
                {
                    currentquality.CLCode = quality.CLCode;
                }
                if (quality.CSCode != null)
                {
                    currentquality.CSCode = quality.CSCode;
                }
                if (quality.dogid != null)
                {
                    currentquality.dogid = quality.dogid;
                }
                if (quality.EmpGuid != null)
                {
                    currentquality.EmpGuid = quality.EmpGuid;
                }
                if (quality.EmpType != null)
                {
                    currentquality.EmpType = quality.EmpType;
                }
                if (quality.FlowCode != null)
                {
                    currentquality.FlowCode = quality.FlowCode;
                }
                if (quality.GetCertificateDate != null)
                {
                    currentquality.GetCertificateDate = quality.GetCertificateDate;
                }
                if (quality.IsDel != null)
                {
                    currentquality.IsDel = quality.IsDel;
                }
                else
                {
                    currentquality.IsDel = false;
                }
                if (quality.IsExport != null)
                {
                    currentquality.IsExport = quality.IsExport;
                }
                if (quality.IsValid != null)
                {
                    currentquality.IsValid = quality.IsValid;
                }
                if (quality.oldid != null)
                {
                    currentquality.oldid = quality.oldid;
                }
                if (quality.pxzhenghao != null)
                {
                    currentquality.pxzhenghao = quality.pxzhenghao;
                }
                if (quality.StampCode != null)
                {
                    currentquality.StampCode = quality.StampCode;
                }
                if (quality.TreeID != null)
                {
                    currentquality.TreeID = quality.TreeID;
                }
                if (quality.TypeFlags != null)
                {
                    currentquality.TypeFlags = quality.TypeFlags;
                }
                if (quality.zczhenghao != null)
                {
                    currentquality.zczhenghao = quality.zczhenghao;
                }
                if (quality.zczhuanye1 != null)
                {
                    currentquality.zczhuanye1 = quality.zczhuanye1;
                }
                if (quality.zczhuanye2 != null)
                {
                    currentquality.zczhuanye2 = quality.zczhuanye2;
                }
                if (quality.ZsEndDate != null)
                {
                    currentquality.ZsEndDate = quality.ZsEndDate;
                }
                if (quality.ZsRegisterDate != null)
                {
                    currentquality.ZsRegisterDate = quality.ZsRegisterDate;
                }
            }
            return qdcontext.SaveChanges();
        }

        /// <summary>
        /// 修改tb_flowcode的状态
        /// </summary>
        /// <param name="empguid"></param>
        /// <param name="flowcode"></param>
        /// <returns></returns>
        private int ModityManagerStatus(string empguid, string flowcode)
        {
            try
            {
                Guid eguid = new Guid(empguid);
                var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == eguid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                if (dbEmp != null)
                {
                    dbEmp.FlowCode = flowcode;
                    qdcontext.SaveChanges();
                }

                //Tb_FlowCode flowcodemodel = qdcontext.FlowCodes.Where(f => f.ObjectId == empguid && f.IsDel == false && f.CodeType == 8000).FirstOrDefault();
                //if (flowcodemodel != null)
                //{
                //    flowcodemodel.FlowCode = flowcode;
                //    return qdcontext.SaveChanges();
                //}
            }
            catch
            {
                return 0;
            }
            return 0;
        }

        /// <summary>
        /// 添加人员工作经历
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="workExps"></param>
        private void AddWorkExp(string empGuid, IList<tb_WorkExperience> workExps)
        {
            try
            {
                Guid eGuid = Guid.Empty;
                if (!Guid.TryParse(empGuid, out eGuid))
                {
                    return;
                }
                tb_Emp_Manager currentManager = qdcontext.Emp_Manager.Where(m => m.EmpGuid == eGuid && (m.IsDel != true || m.IsDel == null)).FirstOrDefault();
                if (currentManager != null)
                {
                    foreach (tb_WorkExperience workexp in workExps)
                    {
                        workexp.CorpGuid = Guid.NewGuid();
                        qdcontext.WorkExperience.Add(workexp);
                        qdcontext.SaveChanges();
                        ////记录日志
                        loghelper.InsertUserLog("添加人员工作经历成功", workexp.ID.ToString(), "8050", "1");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
        }

        /// <summary>
        /// 修改人员工作经历
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="workExps"></param>
        private void EmpWorkExpEdit(string empGuid, IList<tb_WorkExperience> workExps)
        {
            try
            {
                Guid eGuid = Guid.Empty;
                if (!Guid.TryParse(empGuid, out eGuid))
                {
                    return;
                }
                ////删除
                var dbWorkExps = qdcontext.WorkExperience.Where(p => p.EmpGuid == eGuid).ToList();
                foreach (var expitem in dbWorkExps)
                {
                    qdcontext.WorkExperience.Remove(expitem);
                    qdcontext.SaveChanges();
                }
                ////添加
                AddWorkExp(empGuid, workExps);

            }
            catch (Exception ex)
            {

                throw ex.InnerException;
            }
        }

        /// <summary>
        /// 添加人员资质
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <returns></returns>
        private bool AddTitleDetail(string corpuserguid, string empGuid, IList<Tb_Emp_TitleDetails> empQualities)
        {
            try
            {
                Guid eGuid = Guid.Empty;
                if (!Guid.TryParse(empGuid, out eGuid))
                {
                    return false;
                }
                tb_Emp_Manager currentManager = qdcontext.Emp_Manager.Where(m => m.EmpGuid == eGuid && (m.IsDel != true || m.IsDel == null)).FirstOrDefault();
                if (currentManager != null)
                {
                    foreach (Tb_Emp_TitleDetails titledetail in empQualities)
                    {
                        Tb_Emp_TitleDetails emptitledetail = qdcontext.Emp_Qualities.Where(t => t.EmpGuid == new Guid(empGuid) && t.EducationGUID == titledetail.EducationGUID && (t.IsDel != true || t.IsDel == null)).FirstOrDefault();
                        if (emptitledetail == null)
                        {
                            titledetail.IsDel = false;
                            if (titledetail.EducationGUID == Guid.Empty)
                            {
                                titledetail.EducationGUID = Guid.NewGuid();
                            }

                            titledetail.EmpGuid = new Guid(empGuid);
                            titledetail.FlowCode = "0";
                            qdcontext.Emp_Qualities.Add(titledetail);
                            qdcontext.SaveChanges();
                            ////记录流程状态
                            //AddFlowCode(titledetail.EducationGUID.ToString(), 8040, "");
                            ////记录日志
                            loghelper.InsertUserLog("添加人员资质成功", titledetail.EducationGUID.ToString(), "8040", "1");
                        }
                    }
                }
                else
                {
                    tb_Emp_Manager managermodel = new tb_Emp_Manager();
                    managermodel.EmpGuid = new Guid(empGuid);
                    managermodel.IsDel = false;
                    managermodel.IsExit = false;
                    managermodel.CorpGuid = new Guid(corpuserguid);
                    managermodel.FlowCode = "0";
                    qdcontext.Emp_Manager.Add(managermodel);
                    qdcontext.SaveChanges();
                    foreach (Tb_Emp_TitleDetails titledetail in empQualities)
                    {
                        Tb_Emp_TitleDetails emptitledetail = qdcontext.Emp_Qualities.Where(t => t.EmpGuid == new Guid(empGuid) && t.EducationGUID == titledetail.EducationGUID && t.IsDel == false).FirstOrDefault();
                        if (emptitledetail == null)
                        {
                            titledetail.IsDel = false;
                            if (titledetail.EducationGUID == Guid.Empty)
                            {
                                titledetail.EducationGUID = Guid.NewGuid();
                            }

                            titledetail.EmpGuid = new Guid(empGuid);
                            titledetail.FlowCode = "0";
                            qdcontext.Emp_Qualities.Add(titledetail);
                            qdcontext.SaveChanges();
                            ////记录流程状态
                            //AddFlowCode(titledetail.EducationGUID.ToString(), 8040, "");
                            ////记录日志
                            loghelper.InsertUserLog("添加人员资质成功", titledetail.EducationGUID.ToString(), "8040", "1");
                        }
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 企业为人员变更资质证书
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private void EmpQualityPrivateEdit(string empGuid, IList<Tb_Emp_TitleDetails> empQualities)
        {
            Guid eGuid = Guid.Empty;
            Guid.TryParse(empGuid, out eGuid);

            ////删除
            var dbQualities = qdcontext.Emp_Qualities.Where(p => p.EmpGuid == eGuid).ToList();
            foreach (var qitem in dbQualities)
            {
                qdcontext.Emp_Qualities.Remove(qitem);
                qdcontext.SaveChanges();
            }

            ////1.更改人员资格。
            try
            {
                foreach (Tb_Emp_TitleDetails empQuality in empQualities)
                {
                    if (empQuality.IsDel == null || empQuality.IsDel != true)
                    {
                        //empQuality.IsDel = false;
                        empQuality.EmpGuid = new Guid(empGuid);
                        if (empQuality.EducationGUID == Guid.Empty)
                        {
                            empQuality.EducationGUID = Guid.NewGuid();
                        }
                        qdcontext.Emp_Qualities.Add(empQuality);
                        qdcontext.SaveChanges();
                        ////记录流程状态
                        AddFlowCode(empQuality.EducationGUID.ToString(), 8040, "");
                        ////记录日志
                        loghelper.InsertUserLog("添加人员资质成功", empQuality.EducationGUID.ToString(), "8040", "1");
                    }
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
            }
        }

        /// <summary>
        /// 获取能压证数量
        /// </summary>
        /// <param name="typeFlag">角色</param>
        /// <param name="bGrade">企业类型</param>
        /// <param name="level">级别</param>
        /// <returns>int</returns>
        private int CheckManagerRole(string typeFlag, int? bGrade, string level)
        {
            int canPledgeCounts = 0;
            if (typeFlag == "2" && bGrade == 42)////监理企业项目总监
            {
                switch (level)
                {
                    case "1":
                        canPledgeCounts = 3;
                        break;
                    case "2":
                        canPledgeCounts = 2;
                        break;
                    case "3":
                        canPledgeCounts = 1;
                        break;
                }
            }
            else if (bGrade == 15 || bGrade == 17)////施工企业项目经理
            {
                if (typeFlag == "0" || typeFlag == "1")
                {
                    canPledgeCounts = 1;
                }
            }
            return canPledgeCounts;
        }

        /// <summary>
        /// 根据TypeFlag获取functionId。
        /// </summary>
        /// <param name="typeFlag"></param>
        /// <returns></returns>
        private int GetEmployeeType(int typeFlag)
        {
            switch (typeFlag)
            {
                case 3:
                    return 8001;
                case 4:
                    return 8002;
                case 5:
                    return 8003;
                case 7:
                    return 8004;
                case 8:
                    return 8005;
                case 9:
                    return 8006;
                default:
                    return 0;
            }
        }

        /// <summary>
        /// 获取管理人员编号。
        /// </summary>
        /// <returns></returns>
        private IList<int> GetEmployeeTypeFlag()
        {
            return new List<int> { 3, 4, 5, 7, 8, 6, 11, 15, 9, 10 };
        }

        /// <summary>
        /// 根据corpUserGuid与CodeType=8001获取最新一次的变更审核记录
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        private Tb_FlowCode GetEmployeeNewOneChangeStatus(string corpUserGuid)
        {
            var flowCode = qdcontext.FlowCodes.Where(f => f.ObjectId == corpUserGuid && f.CodeType == 8001).OrderByDescending(fo => fo.UpdateTime).FirstOrDefault();
            return flowCode;

        }

        /// <summary>
        /// 根据ChangeSetID与CodeType=8008获取最新一次的变更审核记录
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        private Tb_FlowCode GetPersonEntryExitOneChangeStatus(string changeSetID)
        {
            var flowCode = qdcontext.FlowCodes.Where(f => f.ObjectId == changeSetID && f.CodeType == 8008).OrderByDescending(fo => fo.UpdateTime).FirstOrDefault();
            return flowCode;

        }

        /// <summary>
        /// tb_Emp_Employee修改赋值
        /// </summary>
        /// <param name="newEmp"></param>
        /// <param name="itemOld"></param>
        private void SetEmployeeEntityValue(tb_Emp_Employee newEmp, tb_Emp_Employee itemOld)
        {
            if (newEmp.ACode != null)
            {
                itemOld.ACode = newEmp.ACode;
            }
            if (newEmp.AlterDateTime != null)
            {
                itemOld.AlterDateTime = newEmp.AlterDateTime;
            }
            if (newEmp.AlterForwardID != null)
            {
                itemOld.AlterForwardID = newEmp.AlterForwardID;
            }
            if (newEmp.AQKHFZDW != null)
            {
                itemOld.AQKHFZDW = newEmp.AQKHFZDW;
            }
            if (newEmp.AqzsCode != null)
            {
                itemOld.AqzsCode = newEmp.AqzsCode;
            }
            if (newEmp.AqzsEndDate != null)
            {
                itemOld.AqzsEndDate = newEmp.AqzsEndDate;
            }
            if (newEmp.AqzsGetDate != null)
            {
                itemOld.AqzsGetDate = newEmp.AqzsGetDate;
            }
            if (newEmp.BrithDay != null)
            {
                itemOld.BrithDay = newEmp.BrithDay;
            }
            if (newEmp.Certificatid != null)
            {
                itemOld.Certificatid = newEmp.Certificatid;
            }
            if (newEmp.CheckComment != null)
            {
                itemOld.CheckComment = newEmp.CheckComment;
            }
            if (newEmp.CZNum != null)
            {
                itemOld.CZNum = newEmp.CZNum;
            }
            if (newEmp.CZRatio != null)
            {
                itemOld.CZRatio = newEmp.CZRatio;
            }
            if (newEmp.DoMajor != null)
            {
                itemOld.DoMajor = newEmp.DoMajor;
            }
            if (newEmp.Education != null)
            {
                itemOld.Education = newEmp.Education;
            }
            if (newEmp.FlowCode != null)
            {
                itemOld.FlowCode = newEmp.FlowCode;
            }
            if (newEmp.GraduatedSchool != null)
            {
                itemOld.GraduatedSchool = newEmp.GraduatedSchool;
            }
            if (newEmp.IDCardAddress != null)
            {
                itemOld.IDCardAddress = newEmp.IDCardAddress;
            }
            if (newEmp.IsBuLu != null)
            {
                itemOld.IsBuLu = newEmp.IsBuLu;
            }
            if (newEmp.JiGuan != null)
            {
                itemOld.JiGuan = newEmp.JiGuan;
            }
            if (newEmp.Job != null)
            {
                itemOld.Job = newEmp.Job;
            }
            if (newEmp.JobAS != null)
            {
                itemOld.JobAS = newEmp.JobAS;
            }
            if (newEmp.MinZu != null)
            {
                itemOld.MinZu = newEmp.MinZu;
            }
            if (newEmp.mobile != null)
            {
                itemOld.mobile = newEmp.mobile;
            }
            if (newEmp.Name != null)
            {
                itemOld.Name = newEmp.Name;
            }
            if (newEmp.Profession != null)
            {
                itemOld.Profession = newEmp.Profession;
            }
            if (newEmp.Resume != null)
            {
                itemOld.Resume = newEmp.Resume;
            }
            if (newEmp.Sex != null)
            {
                itemOld.Sex = newEmp.Sex;
            }
            if (newEmp.Speciality != null)
            {
                itemOld.Speciality = newEmp.Speciality;
            }
            if (newEmp.StartYear != null)
            {
                itemOld.StartYear = newEmp.StartYear;
            }
            if (newEmp.SumTime != null)
            {
                itemOld.SumTime = newEmp.SumTime;
            }
            if (newEmp.tel != null)
            {
                itemOld.tel = newEmp.tel;
            }
            if (newEmp.TitleCode != null)
            {
                itemOld.TitleCode = newEmp.TitleCode;
            }
            if (newEmp.TitleType != null)
            {
                itemOld.TitleType = newEmp.TitleType;
            }
            if (newEmp.zgzcCode != null)
            {
                itemOld.zgzcCode = newEmp.zgzcCode;
            }
            if (newEmp.ZJCertificateCode != null)
            {
                itemOld.ZJCertificateCode = newEmp.ZJCertificateCode;
            }
        }

        /// <summary>
        /// 根据userguid查询用户信息
        /// </summary>
        /// <param name="userguid"></param>
        /// <returns></returns>
        private T_Sys_Users GetSysUserInfo(string userguid)
        {
            T_Sys_Users user = qdcontext.T_Sys_Users.SingleOrDefault(u => u.UserGuid == new Guid(userguid));
            return user;
        }
        #endregion

        #region 人员基本信息相关

        /// <summary>
        /// 查询身份证号是否存在。
        /// </summary>
        /// <param name="idcard"></param>
        /// <returns></returns>
        public override bool IsIDCardExists(string idcard, string areaCode)
        {
            try
            {
                var person = qdcontext.Emp_Manager.FirstOrDefault(r => r.IDCard == idcard);
                if (person != null)
                    return true;
            }
            catch (Exception ex)
            { }
            return false;
        }

        /// <summary>
        /// 获取企业下的管理人员信息。
        /// </summary>
        /// <param name="corpUserGuid">企业编号。</param>
        /// <returns></returns>
        public override string GetPersonManagers(string corpUserGuid, string condition, string areaCode)
        {
            var list = new List<tb_Emp_Employee>();
            // OperationResult rst = null;
            try
            {
                if (!string.IsNullOrEmpty(corpUserGuid))
                {
                    if (!StringHelper.SqlFilter(condition))
                    {
                        list = new PersonDAL().GetPersonManagers(corpUserGuid, condition);
                    }

                }
            }
            catch (Exception ex)
            {
                //rst = new OperationResult { Result = false, Message = "Guid转换出错或查询出错", ReturnValue = personlist };
            }
            return JsonConvert.SerializeObject(list);

        }


        /// <summary>
        /// 获取企业下的普通工人信息。
        /// </summary>
        /// <param name="corpUserGuid">企业编号。</param>
        /// <returns></returns>
        public override string GetPersonEmployee(string corpUserGuid, string condition, string areaCode)
        {
            var list = new List<tb_Emp_Manager>();
            try
            {
                if (!string.IsNullOrEmpty(corpUserGuid))
                {
                    if (!StringHelper.SqlFilter(condition))
                    {
                        list = new PersonDAL().GetPersonEmployee(corpUserGuid, condition);
                    }

                }
            }
            catch
            {
            }
            return JsonConvert.SerializeObject(list);
        }

        public override string GetPersonEmployeeByQulityId(string qulityId, string areaCode)
        {
            var list = new List<tb_Emp_Manager>();
            try
            {
                if (!StringHelper.SqlFilter(qulityId))
                {
                    list = new PersonDAL().GetPersonEmployeeByQualityId(qulityId);
                }
            }
            catch (Exception ex)
            {
            }
            return JsonConvert.SerializeObject(list);
        }

        public override string GetPersonEmployeeByQulityBId(string qulityBId, string areaCode)
        {
            var list = new List<tb_Emp_Manager>();
            try
            {
                if (!StringHelper.SqlFilter(qulityBId))
                {
                    list = new PersonDAL().GetPersonEmployeeByQualityBId(qulityBId);
                }
            }
            catch (Exception ex)
            {
            }
            return JsonConvert.SerializeObject(list);
        }
        /// <summary>
        /// 人员押证查询-获取人员信息（多项）
        /// 返回字符样式：
        /// 成功：0,empID:typeFlag:Bgrade:CertificateLevel|empID:typeFlag:Bgrade:CertificateLevel
        /// 失败：1,XXXXX
        /// </summary>
        /// <param name="empIds"></param>
        /// <returns></returns>
        public override string GetPersonForXMFZR(string empIds, string areaCode)
        {
            string result = string.Empty;

            IList<Guid> empGuids = new List<Guid>();
            if (string.IsNullOrEmpty(empIds))
            {
                result = "9,人员empGuid不能为空.";
            }
            else
            {
                foreach (string empId in empIds.Split(','))
                {
                    Guid empGuid = Guid.Empty;
                    Guid.TryParse(empId, out empGuid);
                    empGuids.Add(empGuid);
                }

                IList<DTO.V_CheckXMFZR> managers = GetXMFZRQuery().Where(p => empGuids.Contains(p.EmpGuid)).ToList();
                foreach (DTO.V_CheckXMFZR item in managers)
                {
                    string bGrade = "0";
                    if (item.bGrade != null)
                    {
                        bGrade = item.bGrade.ToString();
                    }
                    ////返回人员信息，作为项目库中查询押证的参数
                    result = item.ID + ":" + item.TypeFlag + ":" + bGrade + ":" + item.CertificateLevel + "|";
                }
                if (!string.IsNullOrEmpty(result))
                {
                    result = result.TrimEnd('|');
                }
                result = "0," + result;
            }
            return JsonConvert.SerializeObject(result);
        }

        /// <summary>
        /// 根据人员编号查询人员信息。
        /// </summary>
        /// <param name="userId">人员编号。</param>
        /// <returns></returns>
        public override string GetPersonInfo(string userId, string areaCode)
        {
            var model = new tb_Emp_Manager();
            try
            {
                if (!string.IsNullOrEmpty(userId))
                {
                    int iUserId = 0;
                    if (int.TryParse(userId, out iUserId))
                    {

                        model = qdcontext.Emp_Manager.Where(r => r.ID == iUserId).FirstOrDefault();
                    }
                    else
                    {
                        Guid gUserId = Guid.Empty;
                        if (Guid.TryParse(userId, out gUserId))
                        {
                            model = qdcontext.Emp_Manager.Where(r => r.EmpGuid == gUserId).FirstOrDefault();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return JsonConvert.SerializeObject(model);
        }

        public override string GetEmpGuid(string id, string areaCode)
        {
            var model = new Tb_Emp_TitleDetails();
            int idint = Convert.ToInt32(id);
            model = qdcontext.Emp_Qualities.Where(r => r.ID == idint).FirstOrDefault();
            if (model != null)
            {
                return model.EmpGuid == null ? new Guid().ToString() : model.EmpGuid.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        public override string AddPersonInfo(string personInfo, string areaCode)
        {
            OperationResult rst = null;
            try
            {
                if (!string.IsNullOrEmpty(personInfo))
                {
                    tb_Emp_Manager model = JsonConvert.DeserializeObject<tb_Emp_Manager>(personInfo);
                    if (model.IsDel == null || model.IsDel == true)
                    {
                        model.IsDel = false;
                    }
                    model.IsExit = false;
                    qdcontext.Emp_Manager.Add(model);
                    qdcontext.SaveChanges();
                    rst = new OperationResult { Result = true, Message = "操作成功", ReturnValue = "" };
                }
            }
            catch (Exception ex)
            {
                rst = new OperationResult { Result = false, Message = "操作出错", ReturnValue = "" };
            }
            return JsonConvert.SerializeObject(rst);
        }

        public override string EditPersonInfo(string personId, string personInfo, string areaCode)
        {
            OperationResult rst = null;
            string error = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(personInfo))
                {
                    tb_Emp_Manager olderManager = qdcontext.Emp_Manager.Find(personId);
                    tb_Emp_Manager manager = JsonConvert.DeserializeObject<tb_Emp_Manager>(personInfo);
                    if (manager.IsDel == null)
                    {
                        manager.IsDel = false;
                    }
                    if (manager.IsExit == null)
                    {
                        manager.IsExit = false;
                    }
                    EntityHelper.ConvertEntity2Entity<tb_Emp_Manager>(manager, olderManager);
                    qdcontext.SaveChanges();
                    rst = new OperationResult { Result = true, Message = "操作成功", ReturnValue = "" };
                }
            }
            catch (Exception ex)
            {
                rst = new OperationResult { Result = false, Message = "操作出错", ReturnValue = "" };
            }
            return JsonConvert.SerializeObject(rst);
        }

        public override string DeletePersonInfo(string personId, string areaCode)
        {
            OperationResult rst = null;
            string error = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(personId))
                {
                    int id = Convert.ToInt32(personId);
                    tb_Emp_Manager olderManager = qdcontext.Emp_Manager.Where(m => m.ID == id).FirstOrDefault();
                    olderManager.IsDel = true;
                    qdcontext.SaveChanges();
                    rst = new OperationResult { Result = true, Message = "操作成功", ReturnValue = "" };
                }
            }
            catch (Exception ex)
            {
                rst = new OperationResult { Result = false, Message = "操作出错", ReturnValue = "" };
            }
            return JsonConvert.SerializeObject(rst);
        }

        public override string SubmitPersonInfo(string personId, string areaCode)
        {
            return null;
        }

        public override string AuditPersonInfo(string personId, string flowCode, string description, bool isFinal, string areaCode)
        {
            return string.Empty;
        }



        #endregion

        #region 获取人员资格相关

        /// <summary>
        /// 获取人员资格项集合。
        /// </summary>
        /// <param name="personType">人员类型。</param>
        /// <returns></returns>
        public override string GetPersonQualityItems(string personType, string areaCode)
        {

            return null;
        }

        /// <summary>
        /// 获取人员资格集合。
        /// </summary>
        /// <param name="userId">人员编号。</param>
        /// <returns></returns>
        public override string GetPersonQualities(string personId, string areaCode)
        {
            IList<Tb_Emp_TitleDetails> qualities = new List<Tb_Emp_TitleDetails>();

            Guid empGuid = Guid.Empty;
            Guid.TryParse(personId, out empGuid);
            qualities = qdcontext.Emp_Qualities.Where(q => q.EmpGuid == empGuid).ToList();

            return JsonConvert.SerializeObject(qualities);
        }

        /// <summary>
        /// 获取资格信息。
        /// </summary>
        /// <param name="qualityId">资格编号。</param>
        /// <returns></returns>
        public override string GetPersonQuality(string qualityId, string areaCode)
        {
            int qid = 0;
            Tb_Emp_TitleDetails quality = new Tb_Emp_TitleDetails();
            if (int.TryParse(qualityId, out qid))
            {
                quality = qdcontext.Emp_Qualities.SingleOrDefault(q => q.ID == qid);
            }
            Guid eduguid = new Guid();
            if (Guid.TryParse(qualityId, out eduguid))
            {
                quality = qdcontext.Emp_Qualities.SingleOrDefault(q => q.EducationGUID == eduguid);
            }
            return JsonConvert.SerializeObject(quality);
        }

        public override string GetPersonBQuality(string personId, string areaCode)
        {
            int pId = 0;
            Guid guid = Guid.Empty;
            if (int.TryParse(personId, out pId))
            {
                PersonDAL pDal = new PersonDAL();
                return JsonConvert.SerializeObject(pDal.GetPersonBQualityById(personId));
            }
            else if (Guid.TryParse(personId, out guid))
            {
                Tb_Emp_TitleDetailsExt bc = qdcontext.BCards.Where(b => b.EmpGuid == guid).FirstOrDefault();
                return JsonConvert.SerializeObject(bc);
            }
            else
            {
                return string.Empty;
            }
        }

        #endregion

        #region 人员信息  作者：张剑
        public override string GetPersonChanges(string corpName, string corpUserGuid, string userName, string flowCode, string areaCode)
        {
            return base.GetPersonChanges(corpName, corpUserGuid, userName, flowCode, areaCode);
        }

        /// <summary>
        /// 获取企业下的普通工人信息列表
        /// </summary>
        /// <param name="corpUserGuid">企业Guid</param>
        /// <param name="condition">sql where</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageSize">条数</param>
        /// <returns></returns>
        public override string GetPersonEmployees(string corpUserGuid, string condition, int pageIndex, int pageSize, out int count, string areaCode)
        {
            count = 0;
            var list = new List<tb_Emp_Manager1>();

            if (!string.IsNullOrEmpty(corpUserGuid))
            {
                if (!StringHelper.SqlFilter(condition))
                {
                    list = new PersonDAL().GetPersonEmployees(corpUserGuid, condition, pageIndex, pageSize, out  count);
                }
            }

            return JsonConvert.SerializeObject(list);
        }


        public override string GetPersonManagersByCorpUserGuid(string corpUserGuid, string condition, int pageIndex, int pageSize, out int count, string type, string areaCode)
        {
            count = 0;
            var list = new List<tb_Emp_Manager1>();

            if (!string.IsNullOrEmpty(corpUserGuid))
            {
                if (!StringHelper.SqlFilter(condition))
                {
                    list = new PersonDAL().GetPersonManagersByCorpUserGuid(corpUserGuid, condition, pageIndex, pageSize, out  count, type);
                }
            }

            return JsonConvert.SerializeObject(list);
        }

        /// <summary>
        /// 获取企业下的普通工人信息列表总记录数
        /// </summary>
        /// <param name="corpUserGuid">企业Guid</param>
        /// <param name="condition">sql where</param>
        /// <returns></returns>
        //public override int GetPersonEmployeesCount(string corpUserGuid, string condition)
        //{
        //    int count = 0;
        //    try
        //    {
        //        if (!string.IsNullOrEmpty(corpUserGuid))
        //        {
        //            if (!StringHelper.SqlFilter(condition))
        //            {
        //                count = new PersonDAL().GetPersonEmployeesCount(corpUserGuid, condition);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //    return count;
        //}

        /// <summary>
        /// 获取企业下的指定工人的证书列表
        /// </summary>
        /// <param name="empGuid">empGuid</param>
        /// <param name="condition">sql where</param>
        /// <returns></returns>
        public override string GetPersonTitleDetails(string empGuid, string condition, string areaCode)
        {
            var list = new List<Tb_Emp_TitleDetails>();
            try
            {
                if (!String.IsNullOrEmpty(empGuid))
                {
                    if (!StringHelper.SqlFilter(condition))
                    {
                        list = new PersonDAL().GetPersonTitleDetails(empGuid, condition);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return JsonConvert.SerializeObject(list);
        }

        #endregion

        #region 人员、人员资质的 增删改、上报、审核  作者：赵娇娇、
        /// <summary>
        /// 企业添加人员信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emp"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoAdd(string corpUserGuid, DTO.tb_Emp_Manager emp, IList<DTO.Tb_Emp_TitleDetails> empQualities, IList<DTO.tb_WorkExperience> workExps, bool isReturnModel, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    if (emp != null)
                    {
                        ////判断身份证是否重复
                        int idcards = qdcontext.Emp_Manager.Where(p => p.IDCard == emp.IDCard && p.CorpGuid == emp.CorpGuid && (p.IsDel != true || p.IsDel == null)).Count();
                        if (idcards > 0)
                        {
                            result.Message = "身份证号重复，人员添加失败";
                            result.Result = false;
                        }
                        else
                        {
                            ////1、添加人员
                            if (emp.EmpGuid == Guid.Empty)
                            {
                                emp.EmpGuid = Guid.NewGuid();
                            }
                            if (emp.IsDel == null || emp.IsDel == true)
                            {
                                emp.IsDel = false;
                            }
                            emp.IsExit = false;
                            Guid corpGuid = new Guid(corpUserGuid);
                            T_Sys_Users corpUser = qdcontext.T_Sys_Users.Where(r => r.UserGuid == corpGuid && r.DogID > 0).FirstOrDefault();
                            if (corpUser != null)
                            {
                                int roleid = corpUser.RoleID ?? 0;
                                if (roleid == 105 || roleid == 99105)
                                    emp.TypeFlag = "103";
                                else
                                    emp.TypeFlag = PersonHelper.CreatePersonTypeFlagbyTitleDetails((corpUser.RoleID ?? 0).ToString(), empQualities);
                                emp.DogID = corpUser.DogID;

                            }
                            tb_Emp_Manager emp_E = new tb_Emp_Manager();
                            EntityHelper.ConvertEntity2OtherEntity(emp, emp_E);

                            emp_E.FlowCode = "0";
                            tb_Emp_Manager manager = qdcontext.Emp_Manager.Add(emp_E);
                            qdcontext.SaveChanges();

                            ////添加人员资质并计入FLOWCODE,不存tb_flowcode表
                            List<Tb_Emp_TitleDetails> empQualities_E = new List<Tb_Emp_TitleDetails>();
                            foreach (DTO.Tb_Emp_TitleDetails item in empQualities)
                            {
                                Tb_Emp_TitleDetails empQuality_E = new Tb_Emp_TitleDetails();
                                if (item.IsDel == null || item.IsDel == true)
                                {
                                    item.IsDel = false;
                                }
                                EntityHelper.ConvertEntity2OtherEntity(item, empQuality_E);
                                empQualities_E.Add(empQuality_E);
                            }
                            AddTitleDetail(corpUserGuid, manager.EmpGuid.ToString(), empQualities_E);

                            ////添加人员主要工作经历
                            List<Entity.QD.tb_WorkExperience> workExps_E = new List<Entity.QD.tb_WorkExperience>();
                            foreach (DTO.tb_WorkExperience item in workExps)
                            {
                                Entity.QD.tb_WorkExperience work_E = new Entity.QD.tb_WorkExperience();
                                EntityHelper.ConvertEntity2OtherEntity(item, work_E);
                                workExps_E.Add(work_E);
                            }
                            AddWorkExp(manager.EmpGuid.ToString(), workExps_E);
                            ////2、记录流程状态
                            //AddFlowCode(m.EmpGuid.ToString(), 8000, "");
                            ////3、记录日志
                            loghelper.InsertUserLog("添加人员成功", manager.EmpGuid.ToString(), "8000", "1");
                            tran.Commit();
                            result.Result = true;
                            if (isReturnModel)
                            {
                                result.ReturnValue = manager;
                            }
                            result.Message = "人员添加成功";
                        }
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员添加失败" + ex.InnerException;
                    result.Result = false;
                }
            }
            return result;
        }

        /// <summary>
        /// 企业修改人员信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoEdit(string corpUserGuid, string roleid, DTO.tb_Emp_Manager emps, IList<DTO.Tb_Emp_TitleDetails> empQualities, IList<DTO.tb_WorkExperience> workExps, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            tb_Emp_Manager currentManager = qdcontext.Emp_Manager.Where(p => p.EmpGuid == emps.EmpGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
            if (currentManager != null)
            {
                using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
                {
                    con.Open();
                    DbTransaction tran = con.BeginTransaction();
                    try
                    {
                        ////判断身份证是否重复
                        int idcards = qdcontext.Emp_Manager.Where(p => p.IDCard == emps.IDCard && p.EmpGuid != emps.EmpGuid && p.CorpGuid == emps.CorpGuid && (p.IsDel != true || p.IsDel == null)).Count();
                        if (idcards > 0)
                        {
                            result.Message = "身份证号重复，人员修改失败";
                            result.Result = false;
                        }
                        else
                        {
                            ////修改资质证书
                            List<Tb_Emp_TitleDetails> empQualities_E = new List<Tb_Emp_TitleDetails>();
                            foreach (DTO.Tb_Emp_TitleDetails item in empQualities)
                            {
                                Tb_Emp_TitleDetails empQuality_E = new Tb_Emp_TitleDetails();
                                if (item.IsDel == null)
                                {
                                    item.IsDel = false;
                                }
                                EntityHelper.ConvertEntity2OtherEntity(item, empQuality_E);
                                empQualities_E.Add(empQuality_E);
                            }
                            EmpQualityPrivateEdit(currentManager.EmpGuid.ToString(), empQualities_E);

                            if (!(emps.TypeFlag == "100" || emps.TypeFlag == "101"))
                            {
                                emps.TypeFlag = PersonHelper.CreatePersonTypeFlagbyTitleDetails(roleid, empQualities);
                            }
                            if (emps.IsDel == null)
                            {
                                emps.IsDel = false;
                            }
                            if (emps.IsExit == null)
                            {
                                emps.IsExit = false;
                            }
                            tb_Emp_Manager emp_E = new tb_Emp_Manager();
                            EntityHelper.ConvertEntity2OtherEntity(emps, emp_E);
                            EntityHelper.ConvertEntity2Entity<tb_Emp_Manager>(emp_E, currentManager);
                            qdcontext.SaveChanges();

                            ////修改工作经历
                            List<tb_WorkExperience> workExps_E = new List<tb_WorkExperience>();
                            foreach (DTO.tb_WorkExperience item in workExps)
                            {
                                Entity.QD.tb_WorkExperience work_E = new Entity.QD.tb_WorkExperience();
                                EntityHelper.ConvertEntity2OtherEntity(item, work_E);
                                workExps_E.Add(work_E);
                            }
                            EmpWorkExpEdit(currentManager.EmpGuid.ToString(), workExps_E);
                            ////2、记录日志
                            loghelper.InsertUserLog("修改人员信息", emps.EmpGuid.ToString(), "8000", "2");
                            tran.Commit();
                            result.Message = "修改人员成功！";
                            result.Result = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "修改人员失败：" + ex.Message;
                        result.Result = false;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 删除基本人员信息
        /// </summary>
        /// <param name="empGuids"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoDel(IList<string> empGuids, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var item in empGuids)
                    {
                        ////1.修改 tb_Emp_Manager
                        ////查询数据库
                        Guid empguid = new Guid(item);
                        var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == empguid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                        ////修改赋值
                        if (dbEmp != null)
                        {
                            if ((dbEmp.FlowCode.StartsWith("1") || dbEmp.FlowCode.StartsWith("0,019")) && !dbEmp.FlowCode.Contains(",021"))
                            {
                                result.Message = "已上报人员、审核通过人员不可删除！";
                                result.Result = false;
                                result.ReturnValue = null;
                                return result;
                            }
                            dbEmp.IsDel = true;
                            qdcontext.SaveChanges();
                            ////2.日志
                            loghelper.InsertUserLog("删除基本人员信息", item, "8000", "3");
                            ////3.关联删除资质 tb_Emp_TitleDetails
                            var dbEmpQualitys = qdcontext.Emp_Qualities.Where(p => p.EmpGuid == empguid && (p.IsDel != true || p.IsDel == null)).ToList();
                            if (dbEmpQualitys != null)
                            {
                                foreach (var quaitem in dbEmpQualitys)
                                {
                                    quaitem.IsDel = true;
                                    qdcontext.SaveChanges();
                                    ////日志
                                    loghelper.InsertUserLog("删除人员资质信息", quaitem.EducationGUID.ToString(), "8040", "3");
                                }
                            }
                            ////4.关联删除工作经历 tb_WorkExperience
                            var dbEmpWorkExps = qdcontext.WorkExperience.Where(p => p.EmpGuid == empguid).ToList();
                            if (dbEmpWorkExps != null)
                            {
                                foreach (var expitem in dbEmpWorkExps)
                                {
                                    qdcontext.WorkExperience.Remove(expitem);
                                    qdcontext.SaveChanges();
                                    ////日志
                                    loghelper.InsertUserLog("删除人员工作经历信息", expitem.ID.ToString(), "8050", "3");
                                }
                            }
                        }
                    }
                    tran.Commit();
                    result.Message = "删除成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "删除失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 企业上报人员信息
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps">人员集合</param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoPost(string corpUserGuid, IList<string> emps, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var item in emps)
                    {
                        Guid empguid = new Guid(item);
                        var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == empguid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                        if (dbEmp != null)
                        {

                            if ((dbEmp.FlowCode.StartsWith("1") || dbEmp.FlowCode.StartsWith("0,019")) && !dbEmp.FlowCode.Contains(",021"))
                            {
                                result.Result = false;
                                result.Message = "【已上报】【审核通过】人员不可以再次上报";
                                return result;
                            }
                            ////如果被退回，则状态为再次上报
                            if (dbEmp.FlowCode == "0,019,021,")
                            {
                                dbEmp.FlowCode = "0,019,022,";
                            }
                            else
                            {
                                dbEmp.FlowCode = "0,019,";
                            }
                            qdcontext.SaveChanges();
                            ////记录详细日志
                            loghelper.InsertDetailUserLog("人员上报成功", item, "8000", "4", log);
                        }
                        //Tb_FlowCode flowcode = qdcontext.FlowCodes.Where(f => f.ObjectId == item && f.CodeType == 8000 && f.IsDel == false).FirstOrDefault();
                        //if (flowcode != null)
                        //{
                        //    flowcode.FlowCode = "0,019";//FlowHelper.GetQdFlowCode(0, 1, false);
                        //    flowcode.UpdateTime = DateTime.Now;
                        //    ////记录详细日志
                        //    loghelper.InsertDetailUserLog("人员上报成功", item, "8000", "4", log);
                        //    qdcontext.SaveChanges();
                        //}
                        //else
                        //{
                        //    flowcode = new Tb_FlowCode();
                        //    flowcode.ObjectId = item;
                        //    flowcode.AreaCode = "02";
                        //    flowcode.CodeType = 8000;
                        //    flowcode.FlowCode = "0,019";
                        //    flowcode.UpdateTime = DateTime.Now;
                        //    flowcode.IsDel = false;
                        //    loghelper.AddFlowcode(flowcode);
                        //    ////记录详细日志
                        //    loghelper.InsertDetailUserLog("人员上报成功", item, "8000", "4", log);
                        //}
                    }
                    tran.Commit();
                    result.Result = true;
                    result.Message = "人员上报成功";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员上报失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 查询tb_Emp_Manager审核状态
        /// </summary>
        /// <param name="empGuid"></param>
        /// <returns></returns>
        public override string GetEmpInfoFlowCode(string empGuid, string areaCode)
        {
            string thisFlowCode = string.Empty;
            Guid empguid = new Guid(empGuid);
            var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == empguid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
            if (dbEmp != null)
            {
                thisFlowCode = dbEmp.FlowCode;
            }
            //Tb_FlowCode flowcode = qdcontext.FlowCodes.Where(f => f.ObjectId == empGuid && f.CodeType == 8000 && f.IsDel == false).FirstOrDefault();
            //if (flowcode != null)
            //{
            //    thisFlowCode = flowcode.FlowCode;
            //}
            return thisFlowCode;
        }

        /// <summary>
        /// 企业更改人员状态
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="flowCode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpStatusEdit(string corpUserGuid, string empGuid, string flowCode, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "传入参数格式不正确";
                return result;
            }
            tb_Emp_Manager currentManager = qdcontext.Emp_Manager.Where(p => p.EmpGuid == eGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
            if (currentManager != null)
            {
                try
                {
                    ////1、修改人员
                    if (ModityManagerStatus(empGuid, flowCode) > 0)
                    {
                        ////2、记录日志
                        loghelper.InsertUserLog("修改人员状态", empGuid, "8000", "2");
                        result.Message = "修改人员状态成功！";
                        result.Result = true;
                    }
                }
                catch (Exception ex)
                {
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "修改人员状态失败：" + ex.Message;
                    result.Result = true;
                }
            }
            return result;
        }

        /// <summary>
        /// 企业为人员添加资质
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpQualityAdd(string corpUserGuid, string empGuid, IList<DTO.Tb_Emp_TitleDetails> empQualities, bool isReturnModel, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                ////1.更改人员资格。
                try
                {
                    ////1、添加人员资质 不计入tb_flowcode
                    List<Tb_Emp_TitleDetails> empQualities_E = new List<Tb_Emp_TitleDetails>();
                    foreach (DTO.Tb_Emp_TitleDetails item in empQualities)
                    {
                        if (item.IsDel == null)
                        {
                            item.IsDel = false;
                        }
                        Tb_Emp_TitleDetails empQuality_E = new Tb_Emp_TitleDetails();
                        EntityHelper.ConvertEntity2OtherEntity(item, empQuality_E);
                        empQualities_E.Add(empQuality_E);
                    }
                    AddTitleDetail(corpUserGuid, empGuid, empQualities_E);
                    qdcontext.SaveChanges();
                    result.Result = true;
                    result.Message = "人员资质添加成功";
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员资质添加失败" + ex.Message;
                    result.Result = false;
                }
            }
            return result;
        }

        /// <summary>
        /// 删除人员资质
        /// </summary>
        /// <param name="educationGUID"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpQualityDel(string educationGUID, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////1.修改 tb_Emp_TitleDetails
                    ////查询数据库
                    Guid eduguid = new Guid(educationGUID);

                    Tb_Emp_TitleDetails dbEmpQuality = qdcontext.Emp_Qualities.Where(p => p.EducationGUID == eduguid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                    ////修改赋值
                    if (dbEmpQuality != null)
                    {
                        dbEmpQuality.IsDel = true;
                    }
                    qdcontext.SaveChanges();
                    ////2.日志
                    loghelper.InsertUserLog("删除人员资质信息", dbEmpQuality.EducationGUID.ToString(), "8040", "3");
                    tran.Commit();
                    result.Message = "删除成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "删除失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 企业为人员上报资质
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpQualityPost(string corpUserGuid, string empGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "传入参数格式不正确";
                return result;
            }
            IList<Tb_Emp_TitleDetails> empQualities = qdcontext.Emp_Qualities.Where(t => t.EmpGuid == eGuid && (t.IsDel != true || t.IsDel == null)).ToList();
            if (empQualities != null && empQualities.Count > 0)
            {
                using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
                {
                    con.Open();
                    DbTransaction tran = con.BeginTransaction();
                    try
                    {
                        foreach (Tb_Emp_TitleDetails item in empQualities)
                        {
                            Tb_Emp_TitleDetails dbEmpQuality = qdcontext.Emp_Qualities.Where(p => p.EducationGUID == item.EducationGUID && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                            if (dbEmpQuality != null)
                            {
                                ////如果被退回，则状态为再次上报
                                if (dbEmpQuality.FlowCode.StartsWith("0,019,021"))
                                {
                                    dbEmpQuality.FlowCode = "0,019,022,";
                                }
                                else
                                {
                                    dbEmpQuality.FlowCode = "0,019,";
                                }

                                loghelper.InsertUserLog("人员资质上报成功", empGuid, "8040", "4");
                                qdcontext.SaveChanges();
                            }
                            //Tb_FlowCode flowcode = qdcontext.FlowCodes.Where(f => f.ObjectId == item.EducationGUID.ToString() && f.CodeType == 8040 && f.IsDel == false).FirstOrDefault();
                            //if (flowcode != null)
                            //{
                            //    flowcode.FlowCode = "0,019";// FlowHelper.GetQdFlowCode(1, 0, false);
                            //    flowcode.UpdateTime = DateTime.Now;
                            //    ////记录日志。
                            //    loghelper.InsertUserLog("人员资质上报成功", empGuid, "8040", "4");
                            //    qdcontext.SaveChanges();
                            //}
                        }
                        tran.Commit();
                        result.Result = true;
                        result.Message = "人员资质上报成功";
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "人员资质上报失败：" + ex.Message;
                        result.Result = false;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 企业为人员变更资质证书
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="empGuid"></param>
        /// <param name="empQualities"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpQualityEdit(string corpUserGuid, string empGuid, IList<DTO.Tb_Emp_TitleDetails> empQualities, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.Message = "传入参数格式不正确";
                return result;
            }
            foreach (var empquality in empQualities)
            {
                if (empquality.EmpGuid != eGuid)
                {
                    result.Result = false;
                    result.Message = "该人员不包含此资质";
                    return result;
                }
            }

            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                ////1.更改人员资格。
                try
                {
                    foreach (DTO.Tb_Emp_TitleDetails empQuality in empQualities)
                    {
                        Tb_Emp_TitleDetails empQuality_E = new Tb_Emp_TitleDetails();
                        if (empQuality.IsDel == null)
                        {
                            empQuality.IsDel = false;
                        }
                        EntityHelper.ConvertEntity2OtherEntity(empQuality, empQuality_E);
                        Tb_Emp_TitleDetails empquality1 = qdcontext.Emp_Qualities.SingleOrDefault(q => q.EducationGUID == empQuality.EducationGUID);
                        if (empquality1 != null)
                        {
                            ////赋值。
                            ModityManagerQuality(empquality1, empQuality_E);
                            qdcontext.SaveChanges();
                            ////记录日志。
                            loghelper.InsertUserLog("修改人员资质信息", empGuid, "8040", "2");
                        }

                    }
                    tran.Commit();
                    result.Result = true;
                    result.Message = "修改人员资质信息成功";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Result = false;
                    result.Message = ex.Message;
                }
            }
            return result;
        }

        /// <summary>
        /// 根据人员身份证号信息查询是否注册
        /// </summary>
        /// <param name="idCard"></param>
        /// <returns></returns>
        public override string EmpRegisterValidation(string idCard, string areaCode)
        {
            EmpRegisterValidationModel model = new EmpRegisterValidationModel
            {
                IsRegister = false,
                Manager = null
            };
            tb_Emp_Manager manager = qdcontext.Emp_Manager.Where(m => m.IDCard == idCard && (m.IsDel != true || m.IsDel == null)).FirstOrDefault();
            if (manager != null)
            {
                model.IsRegister = true;
                model.Manager = manager;
            }
            model.Message = idCard;
            return JsonConvert.SerializeObject(model);
        }

        /// <summary>
        /// 查询企业人员详情
        /// </summary>
        /// <param name="corpuserguid"></param>
        /// <param name="empguid"></param>
        /// <returns></returns>
        public override string GetEmployManagerInfo(string corpuserguid, string empguid, string areaCode)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empguid, out eGuid))
            {
                return string.Empty;
            }
            tb_Emp_Manager manager = qdcontext.Emp_Manager.Where(m => m.EmpGuid == eGuid && (m.IsDel != true || m.IsDel == null)).FirstOrDefault();
            if (manager != null)
            {
                return JsonConvert.SerializeObject(manager);
            }
            return string.Empty;
        }

        /// <summary>
        /// 查询企业人员资质
        /// </summary>
        /// <param name="empguid"></param>
        /// <returns></returns>
        public override string GetEmpQualities(string empguid, string areaCode)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empguid, out eGuid))
            {
                return string.Empty;
            }

            IList<Tb_Emp_TitleDetails> qualities = qdcontext.Emp_Qualities.Where(q => q.EmpGuid == eGuid && (q.IsDel != true || q.IsDel == null)).ToList();
            if (qualities != null && qualities.Count > 0)
            {
                return JsonConvert.SerializeObject(qualities);
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取上报人员企业列表
        /// </summary>
        /// <param name="corpname"></param>
        /// <returns></returns>
        public override string GetCorpList(string dogid, string corpname, string corptype, string username, int[] numarr, out int count, int pageIndex, int pageSize, string areaCode)
        {
            int tb_corp_isouter = 0;
            if (!Int32.TryParse(corptype, out tb_corp_isouter))
            {

            }

            DbSet<tb_Emp_Manager> managerlist = qdcontext.Emp_Manager;
            DbSet<T_Sys_Users> userinfolist = qdcontext.T_Sys_Users;
            DbSet<Tb_Corp_CompanyInfo> corpinfolist = qdcontext.Corp_CompanyInfos;


            var query = (from m in managerlist
                         join u in userinfolist
                         on m.CorpGuid equals u.UserGuid
                         join c in corpinfolist
                         on u.UserGuid equals c.CorpUserGuid
                         where numarr.Contains(u.RoleID ?? 0) && u.Name != null && u.UserGuid != Guid.Empty
                         && u.Name.Contains(corpname) && m.FlowCode != "0" && m.FlowCode.IndexOf(",021") < 0 && (m.IsDel == false || m.IsDel == null)
                         && m.Name.Contains(username)
                         select new
                         {
                             corpuserguid = u.UserGuid,
                             corpname = u.Name,
                             roleid = u.RoleID,
                             tb_corp_isouter = c.tb_Corp_IsOuter
                         }).Distinct();

            if (dogid == "206762" || dogid == "1022000")
            {
                query = (from m in managerlist
                         join u in userinfolist
                         on m.CorpGuid equals u.UserGuid
                         join c in corpinfolist
                         on u.UserGuid equals c.CorpUserGuid
                         where numarr.Contains(u.RoleID ?? 0) && u.Name != null && u.UserGuid != Guid.Empty
                         && u.Name.Contains(corpname) && m.FlowCode != "0" && m.FlowCode.IndexOf(",021") < 0 && (m.IsDel == false || m.IsDel == null)
                         && m.Name.Contains(username) && (m.TypeFlag == "0" || m.TypeFlag == "1")
                         select new
                         {
                             corpuserguid = u.UserGuid,
                             corpname = u.Name,
                             roleid = u.RoleID,
                             tb_corp_isouter = c.tb_Corp_IsOuter
                         }).Distinct();
            }

            if (corptype == "-1")
            {
                query = query.Where(q => q.tb_corp_isouter == 1 || q.tb_corp_isouter == 0);
            }
            else
            {
                query = query.Where(q => q.tb_corp_isouter == tb_corp_isouter);
            }



            List<DTO.tbCorpList> lists = new List<DTO.tbCorpList>();
            foreach (var item in query)
            {
                DTO.tbCorpList corp = new DTO.tbCorpList();
                corp.corpuserguid = item.corpuserguid;
                corp.corpname = item.corpname;
                lists.Add(corp);
            }
            count = lists.Count;
            if (count > 0)
            {
                lists = new PersonDAL().GetCorpList(lists);
            }
            lists = lists.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return JsonConvert.SerializeObject(lists);
        }

        public override string GetManagerCount(string dogid, string corpuserguid, string typeflag, string areaCode)
        {
            string countstr = string.Empty;
            var managerlist = qdcontext.Emp_Manager;
            var titleDetails = qdcontext.Emp_Qualities;
            var quary = from m in managerlist
                        select m;
            var quary1 = from m in managerlist
                         select m;
            if (!string.IsNullOrEmpty(corpuserguid))
            {
                Guid? corpguid = new Guid(corpuserguid);
                quary = quary.Where(q => q.CorpGuid == corpguid && (q.IsDel == false || q.IsDel == null));
                quary1 = quary1.Where(q => q.CorpGuid == corpguid && (q.IsDel == false || q.IsDel == null));
            }
            else
            {
                //统计出所有上报、处理的人员数量
                if (dogid == "206762" || dogid == "1022000")
                {
                    quary = quary.Where(q => q.FlowCode.StartsWith("1") && (q.TypeFlag == "0" || q.TypeFlag == "1"));
                    countstr += quary.ToList().Count + ",";
                    quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019") && (q.TypeFlag == "0" || q.TypeFlag == "1"));
                    countstr += quary1.ToList().Count;
                }
                else
                {
                    quary = quary.Where(q => q.FlowCode.StartsWith("1"));
                    countstr += quary.ToList().Count + ",";
                    quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019"));
                    countstr += quary1.ToList().Count;
                }
            }
            if (!string.IsNullOrEmpty(typeflag))
            {
                if (typeflag == "103")
                {
                    quary = quary.Where(q => q.FlowCode.StartsWith("1") && (q.TypeFlag != "100" && q.TypeFlag != "101") && (q.zbdlBusinesscode != null && !q.zbdlBusinesscode.Contains("无")));
                    countstr += quary.ToList().Count + ",";
                    quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019") && q.TypeFlag != "100" && q.TypeFlag != "101" && (q.zbdlBusinesscode != null && !q.zbdlBusinesscode.Contains("无")));
                }
                else if (typeflag == "1031")
                {
                    quary = quary.Where(q => q.FlowCode.StartsWith("1") && (q.TypeFlag != "100" && q.TypeFlag != "101") && (q.zbdlBusinesscode == null || q.zbdlBusinesscode.Contains("无")));
                    countstr += quary.ToList().Count + ",";
                    quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019") && q.TypeFlag != "100" && q.TypeFlag != "101" && (q.zbdlBusinesscode == null || q.zbdlBusinesscode.Contains("无")));
                }
                else if (typeflag == "total")
                {
                    quary = quary.Where(q => q.FlowCode.StartsWith("1"));
                    countstr += quary.ToList().Count + ",";
                    quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019"));
                }
                else if (typeflag == "good" || typeflag == "better" || typeflag == "best")
                {
                    if (typeflag == "good")
                    {
                        //初级
                        quary = quary.Where(q => q.FlowCode.StartsWith("1") && (q.DutyLevel == "1" || q.DutyLevel == "初级"));
                        countstr += quary.ToList().Count + ",";
                        quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019") && (q.DutyLevel == "1" || q.DutyLevel == "初级"));

                    }
                    else if (typeflag == "better")
                    {
                        //中级
                        quary = quary.Where(q => q.FlowCode.StartsWith("1") && (q.DutyLevel == "2" || q.DutyLevel == "中级"));
                        countstr += quary.ToList().Count + ",";
                        quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019") && (q.DutyLevel == "2" || q.DutyLevel == "中级"));

                    }
                    else
                    {
                        //高级
                        quary = quary.Where(q => q.FlowCode.StartsWith("1") && (q.DutyLevel == "3" || q.DutyLevel == "高级"));
                        countstr += quary.ToList().Count + ",";
                        quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019") && (q.DutyLevel == "3" || q.DutyLevel == "高级"));
                    }
                }
                else if (typeflag == "71" || typeflag == "72" || typeflag == "75")
                {
                    return GetManagerCount2(dogid, corpuserguid, typeflag, areaCode);
                }
                else
                {
                    quary = quary.Where(q => q.FlowCode.StartsWith("1") && q.TypeFlag == typeflag);
                    countstr += quary.ToList().Count + ",";
                    quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019") && q.TypeFlag == typeflag);
                }
                countstr += quary1.ToList().Count;
            }
            else
            {
                if (dogid == "206762" || dogid == "1022000")
                {
                    quary = quary.Where(q => q.FlowCode.StartsWith("1") && (q.TypeFlag == "0" || q.TypeFlag == "1"));
                    countstr += quary.ToList().Count + ",";
                    quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019") && (q.TypeFlag == "0" || q.TypeFlag == "1"));
                    countstr += quary1.ToList().Count;
                }
                else
                {
                    quary = quary.Where(q => q.FlowCode.StartsWith("1"));
                    countstr += quary.ToList().Count + ",";
                    quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019"));
                    countstr += quary1.ToList().Count;
                }
            }
            return countstr;
        }

        private string GetManagerCount2(string dogid, string corpuserguid, string typeflag, string areaCode)
        {
            string countstr = string.Empty;
            int typeflags = Convert.ToInt32(typeflag);
            var managerlist = qdcontext.Emp_Manager;
            var titleDetails = qdcontext.Emp_Qualities;

            var quary =  from m in managerlist
                         join t in titleDetails
                         on m.EmpGuid equals t.EmpGuid
                         select new { m.CorpGuid, m.IsDel, m.FlowCode, t.TypeFlags };
            var quary1 = from m in managerlist
                         join t in titleDetails
                         on m.EmpGuid equals t.EmpGuid
                         select new { m.CorpGuid, m.IsDel, m.FlowCode, t.TypeFlags };

            if (!string.IsNullOrEmpty(corpuserguid))
            {
                Guid? corpguid = new Guid(corpuserguid);
                quary = quary.Where(q => q.CorpGuid == corpguid && (q.IsDel == false || q.IsDel == null));
                quary1 = quary1.Where(q => q.CorpGuid == corpguid && (q.IsDel == false || q.IsDel == null));
            }
            
            if (!string.IsNullOrEmpty(typeflag))
            {
                quary = quary.Where(q => q.FlowCode.StartsWith("1") && q.TypeFlags == typeflags);
                countstr += quary.ToList().Count + ",";
                quary1 = quary1.Where(q => !q.FlowCode.StartsWith("1") && !q.FlowCode.Contains("021") && q.FlowCode.StartsWith("0,019") && q.TypeFlags == typeflags);
            }

            return countstr += quary1.ToList().Count;
        }

        /// <summary>
        /// 获取企业人员列表
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public override IList<Entity.ResultModels.tb_Emp_Manager1> GetEmpManagerInfoList(int pageCount, int pageSize, string conditions, string areaCode, string systemid, out int count)
        {
            ////调用DAL中的方法
            var managerlist = new PersonDAL().GetEmpManagerInfoList(pageCount, pageSize, conditions, systemid, out count);
            List<Entity.ResultModels.tb_Emp_Manager1> managerlist_D = new List<Entity.ResultModels.tb_Emp_Manager1>();
            foreach (Entity.ResultModels.tb_Emp_Manager1 item in managerlist)
            {
                Entity.ResultModels.tb_Emp_Manager1 manager_D = new Entity.ResultModels.tb_Emp_Manager1();
                EntityHelper.ConvertEntity2OtherEntity(item, manager_D);
                managerlist_D.Add(manager_D);
            }
            return managerlist_D;
        }

        public override IList<Entity.ResultModels.tb_Emp_Manager1> GetEmpManagerInfoListReg(int pageCount, int pageSize, string conditions, string areaCode, string systemid, out int count)
        {
            ////调用DAL中的方法
            var managerlist = new PersonDAL().GetEmpManagerInfoListReg(pageCount, pageSize, conditions, systemid, out count);
            List<Entity.ResultModels.tb_Emp_Manager1> managerlist_D = new List<Entity.ResultModels.tb_Emp_Manager1>();
            foreach (Entity.ResultModels.tb_Emp_Manager1 item in managerlist)
            {
                Entity.ResultModels.tb_Emp_Manager1 manager_D = new Entity.ResultModels.tb_Emp_Manager1();
                EntityHelper.ConvertEntity2OtherEntity(item, manager_D);
                managerlist_D.Add(manager_D);
            }
            return managerlist_D;
        }

        ///// <summary>
        ///// 获取人员列表
        ///// </summary>
        ///// <param name="pageCount"></param>
        ///// <param name="pageSize"></param>
        ///// <param name="conditions"></param>
        ///// <returns></returns>
        //public override IList<DTO.tb_Emp_Manager> GetEmpManagerList(int pageCount, int pageSize, string conditions)
        //{
        //    ////调用DAL中的方法
        //    var list = new PersonDAL().GetEmpManagerList(pageCount, pageSize, conditions);
        //    List<DTO.tb_Emp_Manager> managerlist_D = new List<DTO.tb_Emp_Manager>();
        //    foreach (tb_Emp_Manager1 item in list)
        //    {
        //        DTO.tb_Emp_Manager manager_D = new DTO.tb_Emp_Manager();
        //        EntityHelper.ConvertEntity2OtherEntity(item, manager_D);
        //        managerlist_D.Add(manager_D);
        //    }
        //    return managerlist_D;
        //}

        /// <summary>
        /// 获取人员列表条数
        /// </summary>
        /// <param name="pageCount"></param>
        /// <param name="pageSize"></param>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public override int GetEmpManagerListCount(string conditions, string areaCode)
        {
            ////调用DAL中的方法
            int str = new PersonDAL().GetEmpManagerListCount(conditions);
            return str;
        }

        /// <summary>
        /// 审核人员信息
        /// </summary>
        /// <param name="empGuids"></param>
        /// <param name="isAuditQualities">是否同时审核人员的资质信息，true表示同时审核</param>
        /// <param name="areaCode"></param>
        /// <param name="log"></param>
        /// <param name="flowCode"></param>
        /// <param name="isFinal"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpInfoAudit(List<string> empGuids, bool isAuditQualities, string areaCode, string log, string flowCode, string description, bool isFinal, bool isunlockandback)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                User_Log loginfo = JsonConvert.DeserializeObject<User_Log>(log);
                if (empGuids != null && empGuids.Count > 0)
                {
                    foreach (string empguid in empGuids)
                    {
                        if (isFinal)
                        {
                            Guid empGuid = new Guid();
                            Guid.TryParse(empguid, out empGuid);

                            var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == empGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                            if (dbEmp != null)
                            {
                                if (!isunlockandback && (dbEmp.FlowCode.StartsWith("1") || dbEmp.FlowCode.StartsWith("0,019,021")))
                                {
                                    result.Result = false;
                                    result.Message = "该人员已被主管审核，无需再次审核，请刷新页面";
                                    return result;
                                }

                                dbEmp.FlowCode = flowCode;
                                dbEmp.Description = description;
                                if (loginfo != null && !string.IsNullOrEmpty(loginfo.Notice))
                                {
                                    dbEmp.Description = loginfo.Notice;
                                }
                                qdcontext.SaveChanges();

                            }

                            if (isAuditQualities)
                            {
                                ////审核人员时同时审核人员资质
                                string empqualities = JsonConvert.SerializeObject(qdcontext.Emp_Qualities.Where(q => q.EmpGuid == new Guid(empguid)).ToList());
                                EmpQualityAudit(empqualities, areaCode, JsonConvert.SerializeObject(log), flowCode, isFinal);
                                result.Result = true;
                                result.Message = "审核企业人员成功";
                            }
                            ////记录日志
                            loghelper.InsertDetailUserLog("审核企业人员成功", empguid, "8000", "4", loginfo);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Message = "审核企业人员失败";
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 审核人员资质信息
        /// </summary>
        /// <param name="qualities"></param>
        /// <param name="areaCode"></param>
        /// <param name="log"></param>
        /// <param name="flowCode"></param>
        /// <param name="isFinal"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmpQualityAudit(string qualities, string areaCode, string log, string flowCode, bool isFinal)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                IList<Tb_Emp_TitleDetails> InfoModels = JsonConvert.DeserializeObject<IList<Tb_Emp_TitleDetails>>(qualities);

                if (InfoModels.Count > 0)
                {
                    foreach (var quality in InfoModels)
                    {
                        if (!isFinal)
                        {

                            Tb_Emp_TitleDetails dbEmpQuality = qdcontext.Emp_Qualities.Where(p => p.EducationGUID == quality.EducationGUID && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                            if (dbEmpQuality != null)
                            {
                                dbEmpQuality.FlowCode = flowCode;
                                ////记录日志
                                loghelper.InsertUserLog("审核人员资质成功", quality.EducationGUID.ToString(), "8000", "4");
                                qdcontext.SaveChanges();
                            }
                            //List<Tb_Emp_TitleDetails> empqualities = qdcontext.Emp_Qualities.Where(q => q.EducationGUID == eduguid && q.IsDel == false).ToList();
                            //foreach (Tb_Emp_TitleDetails titledetail in empqualities)
                            //{
                            //    Tb_FlowCode titledetailflcode = qdcontext.FlowCodes.Where(f => f.ObjectId == titledetail.EducationGUID.ToString() && f.IsDel == false && f.CodeType == 8040).FirstOrDefault();
                            //    if (titledetailflcode != null)
                            //    {
                            //        titledetailflcode.FlowCode = flowCode;
                            //        titledetailflcode.AreaCode = areaCode;
                            //        User_Log loginfo = JsonConvert.DeserializeObject<User_Log>(log);
                            //        titledetailflcode.RoleId = loginfo.IsrtUserRole;
                            //        titledetailflcode.UpdateTime = DateTime.Now;
                            //        ////记录日志
                            //        loghelper.InsertUserLog("审核人员资质成功", quality, "8000", "4");
                            //        qdcontext.SaveChanges();
                            //    }
                            //}
                        }
                    }
                }

                result.Result = true;
                result.Message = "审核人员资质成功";
            }
            catch (Exception ex)
            {
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
                result.Result = false;
                result.Message = "审核人员资质失败";
            }

            return result;
        }

        /// <summary>
        /// 主要工作经历 查询
        /// </summary>
        /// <param name="empguid"></param>
        /// <returns></returns>
        public override IList<DTO.tb_WorkExperience> GetWorkExperienceList(string empguid, string areaCode)
        {
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empguid, out eGuid))
            {
                return null;
            }
            var list = qdcontext.WorkExperience.Where(q => q.EmpGuid == eGuid).ToList();
            List<DTO.tb_WorkExperience> list_D = new List<DTO.tb_WorkExperience>();
            foreach (tb_WorkExperience item in list)
            {
                DTO.tb_WorkExperience work_D = new DTO.tb_WorkExperience();
                EntityHelper.ConvertEntity2OtherEntity(item, work_D);
                list_D.Add(work_D);
            }
            return list_D;
        }

        /// <summary>
        /// 人员主要工作经历添加
        /// </summary>
        /// <param name="workExp"></param>
        /// <returns></returns>
        public override DTO.OperationResult WorkExperienceAdd(DTO.tb_WorkExperience workExp, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    tb_WorkExperience work_E = new tb_WorkExperience();
                    EntityHelper.ConvertEntity2OtherEntity(workExp, work_E);
                    ////添加人员主要工作经历
                    work_E.CorpGuid = Guid.NewGuid();
                    work_E = qdcontext.WorkExperience.Add(work_E);
                    qdcontext.SaveChanges();
                    result.Result = true;
                    result.Message = "人员主要工作经历添加成功";
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员主要工作经历添加失败" + ex.Message;
                    result.Result = false;
                }
            }
            return result;
        }

        /// <summary>
        /// 人员主要工作经历修改
        /// </summary>
        /// <param name="workExp"></param>
        /// <returns></returns>
        public override DTO.OperationResult WorkExperienceEdit(DTO.tb_WorkExperience workExp, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            tb_WorkExperience currentWorkExp = qdcontext.WorkExperience.Where(p => p.EmpGuid == workExp.EmpGuid && p.ID == workExp.ID).FirstOrDefault();
            if (currentWorkExp != null)
            {
                using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
                {
                    con.Open();
                    DbTransaction tran = con.BeginTransaction();
                    try
                    {
                        tb_WorkExperience workExp_E = new tb_WorkExperience();
                        EntityHelper.ConvertEntity2OtherEntity(workExp, workExp_E);
                        EntityHelper.ConvertEntity2Entity<tb_WorkExperience>(workExp_E, currentWorkExp);
                        qdcontext.SaveChanges();
                        result.Message = "修改人员主要工作经历成功！";
                        result.Result = true;
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "修改人员主要工作经历失败：" + ex.Message;
                        result.Result = false;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 设置基本人员为项目主管或项目经办人
        /// </summary>
        /// <param name="empguids"></param>
        /// <param name="corpInfo"></param>
        /// <param name="roleid"></param>
        /// <param name="typeflag"></param>
        /// <param name="typename"></param>
        /// <returns></returns>
        public override DTO.OperationResult SetProjectManger(List<string> empguids, string corpInfo, string roleid, string typeflag, string typename, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    if (empguids != null && empguids.Count > 0)
                    {
                        foreach (string empguid in empguids)
                        {
                            Guid empguid1 = new Guid(empguid);
                            tb_Emp_Manager manager = qdcontext.Emp_Manager.Where(m => m.EmpGuid == empguid1).FirstOrDefault();
                            if (manager.FlowCode != null)
                            {
                                if (manager.FlowCode.IndexOf(",021") < 0 && (manager.FlowCode.StartsWith("0,019") || manager.FlowCode.StartsWith("1")))
                                {
                                    result.Result = false;
                                    result.Message = "已经上报人员、审核通过人员信息不可修改";
                                    return result;
                                }
                            }
                            if (manager != null)
                            {
                                manager.TypeFlag = typeflag;
                                qdcontext.SaveChanges();
                            }
                            if (manager != null)
                            {
                                AddFlowCode(manager.ID.ToString(), 8050, "");
                            }
                        }
                    }
                    tran.Commit();
                    result.Result = true;
                    if (typeflag == "103")
                    {
                        result.Message = "取消人员设置成功";
                    }
                    else
                    {
                        result.Message = "人员设置成功";
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员设置失败：" + ex.Message;
                    result.Result = false;
                }
            }
            return result;
        }

        #endregion

        #region 企业人员管理 （5大员） 作者：
        /// <summary>
        /// 根据typeFlag、corpUserGuid查询详细
        /// </summary>
        /// <returns></returns>     
        public override string GetEmployeeInfo(int typeFlag, string corpUserGuid, string areaCode)
        {
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                return string.Empty;
            }
            tb_Emp_Employee manager = qdcontext.Emp_Employee.Where(m => m.CorpUserGuid == cGuid && m.TypeFlag == typeFlag).FirstOrDefault();
            if (manager != null)
            {
                return JsonConvert.SerializeObject(manager);
            }
            return string.Empty;
        }

        /// <summary>
        /// 查询企业管理人员列表
        /// </summary>
        /// <param name="typeFlags"></param>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Employee> GetEnterpriseEmployeeList(string typeFlags, string corpUserGuid, string areaCode)
        {

            ////调用DAL中的方法
            var managers = new PersonDAL().GetEnterpriseEmployeeList(typeFlags, corpUserGuid);

            List<DTO.tb_Emp_Employee> list_D = new List<DTO.tb_Emp_Employee>();
            foreach (tb_Emp_Employee item in managers)
            {
                DTO.tb_Emp_Employee emp_D = new DTO.tb_Emp_Employee();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        /// <summary>
        /// 主管端
        /// </summary>
        /// <param name="typeFlag"></param>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Employee> GetAdminEmployeeInfoList(string corpUserGuid, string areaCode)
        {
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                return null;
            }
            var managers = qdcontext.Emp_Employee.Where(m => m.CorpUserGuid == cGuid && m.TypeFlag < 0).ToList();
            List<DTO.tb_Emp_Employee> list_D = new List<DTO.tb_Emp_Employee>();
            foreach (tb_Emp_Employee item in managers)
            {
                DTO.tb_Emp_Employee emp_D = new DTO.tb_Emp_Employee();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        /// <summary>
        /// 根据corpUserGuid获取5大员列表
        /// </summary>
        /// <returns></returns>
        public override IList<DTO.tb_Emp_Employee> GetEmployeeInfoList(string corpUserGuid, int type, int systemid, string areaCode)
        {
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                return null;
            }
            IList<tb_Emp_Employee> managerlist = new List<tb_Emp_Employee>();
            if (type == 0)
            {
                managerlist = qdcontext.Emp_Employee.Where(m => m.CorpUserGuid == cGuid && m.TypeFlag > 0 &&
                                                     (m.TypeFlag == 3 || m.TypeFlag == 4 || m.TypeFlag == 5 || m.TypeFlag == 7 || m.TypeFlag == 8 || m.TypeFlag == 9)).Distinct().ToList();
            }
            else
            {
                managerlist = qdcontext.Emp_Employee.Where(m => m.CorpUserGuid == cGuid && m.TypeFlag > 0 &&
                                                        (m.TypeFlag == 3 || m.TypeFlag == 4 || m.TypeFlag == 5 || m.TypeFlag == 7 || m.TypeFlag == 8 || m.TypeFlag == 9
                                                        || m.TypeFlag == 6 || m.TypeFlag == 11 || m.TypeFlag == 15 || m.TypeFlag == 10
                                                        )).Distinct().ToList();
                if (systemid == 2)
                {
                    managerlist = qdcontext.Emp_Employee.Where(m => m.CorpUserGuid == cGuid && m.TypeFlag > 0 &&
                                                      (m.TypeFlag == 3 || m.TypeFlag == 4 || m.TypeFlag == 5 || m.TypeFlag == 7 || m.TypeFlag == 8 || m.TypeFlag == 6 || m.TypeFlag == 11
                                                      )).Distinct().ToList();
                }
            }
            List<DTO.tb_Emp_Employee> list_D = new List<DTO.tb_Emp_Employee>();
            foreach (tb_Emp_Employee item in managerlist)
            {
                DTO.tb_Emp_Employee emp_D = new DTO.tb_Emp_Employee();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        public override IList<DTO.tb_Emp_Employee> GetEmployeeInfoFlowList(string corpUserGuid, int type, string areaCode)
        {
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                return null;
            }
            string flowcode = GetEmployeeChangeStatus(corpUserGuid, areaCode);
            ////调用DAL中的方法
            IList<tb_Emp_Employee> managerlist = new PersonDAL().GetEmployeeInfoFlowList(corpUserGuid, type, flowcode);

            List<DTO.tb_Emp_Employee> list_D = new List<DTO.tb_Emp_Employee>();
            foreach (tb_Emp_Employee item in managerlist)
            {
                DTO.tb_Emp_Employee emp_D = new DTO.tb_Emp_Employee();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        /// <summary>
        /// 添加管理人员信息
        /// </summary>
        /// <param name="emp"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmployeeAdd(DTO.tb_Emp_Employee emp, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();

            if (emp != null)
            {
                ////1、添加人员
                if (emp.EmpGuid == Guid.Empty)
                {
                    emp.EmpGuid = Guid.NewGuid();
                }

                if (!GetEmployeeTypeFlag().Contains((int)emp.TypeFlag))
                {
                    result.Result = false;
                    result.ReturnValue = null;
                    result.Message = "人员添加失败：人员类型不正确！";
                    return result;
                }
                try
                {
                    tb_Emp_Employee emp_E = new tb_Emp_Employee();
                    EntityHelper.ConvertEntity2OtherEntity(emp, emp_E);
                    tb_Emp_Employee manager = qdcontext.Emp_Employee.Add(emp_E);
                    qdcontext.SaveChanges();
                    ////2、记录流程状态
                    //AddFlowCode(m.CorpUserGuid.ToString(), GetEmployeeType((int)emp.TypeFlag), "");
                    ////3、记录日志
                    loghelper.InsertUserLog("添加人员成功", manager.CorpUserGuid.ToString(), GetEmployeeType((int)emp.TypeFlag).ToString(), "1");
                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "人员添加成功";
                }
                catch (Exception ex)
                {
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员添加失败" + ex.InnerException;
                    result.Result = false;
                }

            }
            return result;
        }

        /// <summary>
        /// 修改管理人员信息,由于前台网站只有一个按钮因此只调用修改方法
        /// </summary>
        /// <param name="emp"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmployeeEdit(string corpUserGuid, IList<DTO.tb_Emp_Employee> empList, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "人员修改失败：corpUserGuid不正确！";
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var emp in empList)
                    {
                        if (emp != null)
                        {
                            if (!GetEmployeeTypeFlag().Contains((int)emp.TypeFlag))
                            {
                                result.Result = false;
                                result.ReturnValue = null;
                                result.Message = "人员修改失败：人员类型不正确！";
                                return result;
                            }
                            ////先判断数据库中是否有此数据,如果有就是修改，没有就是添加
                            var oldEmp = qdcontext.Emp_Employee.Where(em => em.CorpUserGuid == cGuid && em.TypeFlag == emp.TypeFlag).FirstOrDefault();
                            if (oldEmp != null)
                            {
                                tb_Emp_Employee emp_E = new tb_Emp_Employee();
                                EntityHelper.ConvertEntity2OtherEntity(emp, emp_E);
                                EntityHelper.ConvertEntity2Entity<tb_Emp_Employee>(emp_E, oldEmp);
                                ////记录日志
                                loghelper.InsertUserLog("人员修改成功", emp.CorpUserGuid.ToString(), GetEmployeeType((int)emp.TypeFlag).ToString(), "2");
                                qdcontext.SaveChanges();

                            }
                            else
                            {
                                result = EmployeeAdd(emp, areaCode);
                            }
                        }

                    }
                    tran.Commit();
                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "人员修改成功";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员修改失败" + ex.InnerException;
                    result.Result = false;
                }
            }

            return result;
        }

        /// <summary>
        /// 添加人员变更信息（需进行审核）
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmployeeChangeAdd(string corpUserGuid, IList<DTO.tb_Emp_Employee> emps, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            ////根据corpUserGuid与CodeType=8001获取最新一次的变更审核记录
            var flowCode = GetEmployeeNewOneChangeStatus(corpUserGuid);

            if (flowCode != null && (flowCode.FlowCode == "0" || flowCode.FlowCode.IndexOf(",021") > 0))
            {
                result = EmployeeChangeEdit(corpUserGuid, emps, areaCode);
            }
            else if (flowCode == null || flowCode.FlowCode.StartsWith("1"))
            {
                using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
                {
                    con.Open();
                    DbTransaction tran = con.BeginTransaction();
                    try
                    {
                        foreach (DTO.tb_Emp_Employee emp in emps)
                        {
                            if (emp != null)
                            {
                                if (emp.TypeFlag > 0)
                                {
                                    int tf = -(int)emp.TypeFlag;
                                    var oldEmp = qdcontext.Emp_Employee.Where(em => em.CorpUserGuid == emp.CorpUserGuid && em.TypeFlag == tf).FirstOrDefault();
                                    if (oldEmp == null)
                                    {
                                        emp.EmpGuid = Guid.NewGuid();
                                        emp.TypeFlag = tf;
                                        tb_Emp_Employee emp_E = new tb_Emp_Employee();
                                        EntityHelper.ConvertEntity2OtherEntity(emp, emp_E);
                                        qdcontext.Emp_Employee.Add(emp_E);
                                    }

                                }

                            }
                        }

                        qdcontext.SaveChanges();
                        ////如果已有flowcode数据则不继续添加
                        var oldflowCode = GetEmployeeNewOneChangeStatus(corpUserGuid);
                        if (oldflowCode == null)
                        {
                            AddFlowCode(corpUserGuid, 8001, "");
                        }
                        loghelper.InsertUserLog("添加人员成功", corpUserGuid, "8001", "1");
                        tran.Commit();
                        result.Result = true;
                        result.ReturnValue = null;
                        result.Message = "人员添加成功";
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "人员添加失败" + ex.InnerException;
                        result.Result = false;
                    }
                }
            }
            else
            {
                result.Message = "此变更的状态不允许修改！";
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 修改人员信息（需进行审核）
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmployeeChangeEdit(string corpUserGuid, IList<DTO.tb_Emp_Employee> emps, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();

            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "人员修改失败：corpUserGuid不正确！";
                return result;
            }
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (DTO.tb_Emp_Employee emp in emps)
                    {
                        int tf = -(int)emp.TypeFlag;
                        var empl = qdcontext.Emp_Employee.Where(em => em.CorpUserGuid == cGuid && em.TypeFlag < 0 && em.TypeFlag == tf).FirstOrDefault();
                        tb_Emp_Employee emp_E = new tb_Emp_Employee();
                        emp.TypeFlag = tf;
                        EntityHelper.ConvertEntity2OtherEntity(emp, emp_E);
                        EntityHelper.ConvertEntity2Entity<tb_Emp_Employee>(emp_E, empl);
                    }
                    qdcontext.SaveChanges();
                    ////记录日志
                    loghelper.InsertUserLog("修改人员成功", corpUserGuid, "8001", "2");
                    tran.Commit();
                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "修改人员成功";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "修改人员成功" + ex.InnerException;
                    result.Result = false;
                }
            }
            return result;
        }

        /// <summary>
        /// 人员信息变更上报
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmployeeChangePost(string corpUserGuid, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            ////根据corpUserGuid与CodeType=8001获取最新一次的变更审核记录
            var flowCode = GetEmployeeNewOneChangeStatus(corpUserGuid);
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    ////判断如果已上报就不再上报

                    if (flowCode.FlowCode.StartsWith("0,019") && !flowCode.FlowCode.Contains(",021"))
                    {
                        result.Message = "人员信息已上报，无需再次上报";
                        result.Result = false;
                    }
                    else
                    {
                        if (flowCode.FlowCode.StartsWith("0,019,021"))
                        {
                            flowCode.FlowCode = "0,019,022,";
                        }
                        else
                        {
                            flowCode.FlowCode = "0,019,";
                        }
                        flowCode.UpdateTime = DateTime.Now;
                        qdcontext.SaveChanges();
                        ////记录日志
                        loghelper.InsertUserLog("人员信息上报成功", corpUserGuid, "8001", "4");
                        tran.Commit();
                        result.Result = true;
                        result.ReturnValue = null;
                        result.Message = "人员信息上报成功";
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员信息上报失败" + ex.InnerException;
                    result.Result = false;
                }
            }

            return result;
        }

        /// <summary>
        /// 人员信息变更审核
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="log"></param>
        /// <param name="flowCode"></param>
        /// <param name="isFinal"></param>
        /// <returns></returns>
        public override DTO.OperationResult EmployeeChangeAudit(string corpUserGuid, string log, string flowCode, string description, bool isFinal, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(corpUserGuid, out cGuid))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "人员审核失败：corpUserGuid不正确！";
                return result;
            }
            ////根据corpUserGuid与CodeType=8001获取最新一次的变更审核记录
            var flow = GetEmployeeNewOneChangeStatus(corpUserGuid);
            ////如果是终审
            if (isFinal)
            {
                ////变更的数据
                var emplNews = qdcontext.Emp_Employee.Where(em => em.CorpUserGuid == cGuid && em.TypeFlag < 0).ToList();
                ////原始数据
                var emplOlds = qdcontext.Emp_Employee.Where(em => em.CorpUserGuid == cGuid && em.TypeFlag > 0).ToList();
                using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
                {
                    con.Open();
                    DbTransaction tran = con.BeginTransaction();
                    try
                    {
                        if (flowCode.StartsWith("1,019,029"))
                        {
                            ////循环原始数据
                            foreach (var itemOld in emplOlds)
                            {
                                ////循环变更数据
                                foreach (var itemNew in emplNews)
                                {
                                    ////比对变更数据与原始数据，确定是对哪一个人的修改
                                    if (itemOld.TypeFlag == -((int)itemNew.TypeFlag) && itemOld.CorpUserGuid == itemNew.CorpUserGuid)
                                    {
                                        SetEmployeeEntityValue(itemNew, itemOld);////用新数据修改原始数据
                                        qdcontext.SaveChanges();
                                    }
                                }
                            }
                            ////删除新数据
                            if (emplOlds != null && emplOlds.Count > 0)
                            {
                                foreach (var itemNew in emplNews)
                                {
                                    qdcontext.Emp_Employee.Remove(itemNew);////删除
                                    qdcontext.SaveChanges();
                                }
                            }
                            else
                            {
                                foreach (var itemNew in emplNews)
                                {
                                    itemNew.TypeFlag = -(int)itemNew.TypeFlag;
                                    qdcontext.SaveChanges();
                                }
                            }
                        }

                        ////流程
                        flow.FlowCode = flowCode;
                        flow.Description = description;
                        flow.UpdateTime = DateTime.Now;
                        qdcontext.SaveChanges();
                        ////记录详细日志
                        User_Log logModel = JsonConvert.DeserializeObject<User_Log>(log);
                        loghelper.InsertDetailUserLog("人员信息修改审核成功", corpUserGuid, "8001", "4", logModel);
                        tran.Commit();
                        result.Result = true;
                        result.ReturnValue = null;
                        result.Message = "人员信息修改审核成功";
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "人员信息修改审核失败" + ex.InnerException;
                        result.Result = false;
                    }
                }
            }
            else
            {
                using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
                {
                    con.Open();
                    DbTransaction tran = con.BeginTransaction();
                    try
                    {
                        flow.FlowCode = flowCode;
                        flow.UpdateTime = DateTime.Now;
                        qdcontext.SaveChanges();
                        ////记录日志
                        loghelper.InsertUserLog("人员信息修改审核成功", corpUserGuid, "8001", "4");
                        tran.Commit();
                        result.Result = true;
                        result.ReturnValue = null;
                        result.Message = "人员信息修改审核成功";
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "人员信息修改审核失败" + ex.InnerException;
                        result.Result = false;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取企业管理人员变更审核状态
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override string GetEmployeeChangeStatus(string corpUserGuid, string areaCode)
        {
            ////根据corpUserGuid与CodeType=8001获取最新一次的变更审核记录
            var flowCode = GetEmployeeNewOneChangeStatus(corpUserGuid);
            if (flowCode != null)
            {
                return flowCode.FlowCode;
            }
            return string.Empty;
        }



        #endregion

        #region 个人端：个人修改密码、主管修改密码、个人验证登录、查询考核结果
        /// <summary>
        /// 个人修改密码
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override DTO.OperationResult UpdatePersonPwd(string empGuid, string pwd, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid eGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out eGuid))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "个人密码修改失败：empGuid不正确！";
                return result;
            }
            var empManager = qdcontext.Emp_Manager.Where(e => e.EmpGuid == eGuid).FirstOrDefault();
            if (empManager != null)
            {
                using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
                {
                    con.Open();
                    DbTransaction tran = con.BeginTransaction();
                    try
                    {
                        empManager.pwd = pwd;
                        qdcontext.SaveChanges();
                        ////记录日志
                        loghelper.InsertUserLog("个人修改密码成功", empGuid, "8000", "2");
                        tran.Commit();
                        result.Result = true;
                        result.ReturnValue = null;
                        result.Message = "个人修改密码成功";
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "个人修改密码失败" + ex.InnerException;
                        result.Result = false;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 主管修改密码
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override DTO.OperationResult UpdateUserPwd(string userGuid, string pwd, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Guid uGuid = Guid.Empty;
            if (!Guid.TryParse(userGuid, out uGuid))
            {
                result.Result = false;
                result.ReturnValue = null;
                result.Message = "主管密码修改失败：userGuid不正确！";
                return result;
            }
            var sysUser = qdcontext.T_Sys_Users.Where(e => e.UserGuid == uGuid).FirstOrDefault();
            if (sysUser != null)
            {
                using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
                {
                    con.Open();
                    DbTransaction tran = con.BeginTransaction();
                    try
                    {
                        sysUser.Pwd = pwd;
                        qdcontext.SaveChanges();
                        ////记录日志
                        loghelper.InsertUserLog("主管修改密码成功", userGuid, "8020", "2");
                        tran.Commit();
                        result.Result = true;
                        result.ReturnValue = null;
                        result.Message = "主管修改密码成功";
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "主管修改密码失败" + ex.InnerException;
                        result.Result = false;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 个人验证登录
        /// </summary>
        /// <param name="IDCard"></param>
        /// <param name="TypeFlag"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override DTO.tb_Emp_Manager ValidPersonLogin(string IDCard, string TypeFlag, string pwd, string areaCode)
        {
            var empManager = qdcontext.Emp_Manager.Where(
                e =>
                e.IDCard == IDCard &&
                e.TypeFlag == TypeFlag &&
                e.pwd == pwd &&
                (e.IsDel != true || e.IsDel == null)
                ).FirstOrDefault();
            DTO.tb_Emp_Manager emp_D = new DTO.tb_Emp_Manager();
            EntityHelper.ConvertEntity2OtherEntity(empManager, emp_D);
            return emp_D;
        }

        /// <summary>
        /// 查询考核结果
        /// </summary>
        /// <param name="IDCard"></param>
        /// <param name="TypeFlag"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override IList<DTO.e_SorcePublish_2006> GetSorcePublishList(int pageIndex, int pageSize, string condition, out int counts, string areaCode)
        {
            ////调用DAL中的方法
            var list = new PersonDAL().GetSorcePublishList(pageIndex, pageSize, condition, out counts);
            List<DTO.e_SorcePublish_2006> list_D = new List<DTO.e_SorcePublish_2006>();
            foreach (e_SorcePublish_2006 item in list)
            {
                DTO.e_SorcePublish_2006 item_D = new DTO.e_SorcePublish_2006();
                EntityHelper.ConvertEntity2OtherEntity(item, item_D);
                list_D.Add(item_D);
            }
            return list_D;
        }

        /// <summary>
        /// 查询考核结果(新2013-5-17)
        /// </summary>
        /// <param name="IDCard"></param>
        /// <param name="TypeFlag"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public override IList<DTO.e_SorcePublish_2006> GetSorcePublishLists(DTO.SorcePublishCondition condition, out int counts, string areaCode)
        {
            ////调用DAL中的方法
            var list = new PersonDAL().GetSorcePublishLists(condition, out counts);
            List<DTO.e_SorcePublish_2006> list_D = new List<DTO.e_SorcePublish_2006>();
            foreach (e_SorcePublish_2006 item in list)
            {
                DTO.e_SorcePublish_2006 item_D = new DTO.e_SorcePublish_2006();
                EntityHelper.ConvertEntity2OtherEntity(item, item_D);
                list_D.Add(item_D);
            }
            return list_D;
        }
        #endregion

        #region 人员押证查询 作者：

        protected override IQueryable<DTO.V_CheckXMFZR> GetXMFZRQuery()
        {
            var dbUsers = qdcontext.T_Sys_Users;
            var dbEmp = qdcontext.Emp_Manager;
            var dbTitleDetails = qdcontext.Emp_Qualities;
            return from users in dbUsers
                   join emps in dbEmp on users.UserGuid equals emps.CorpGuid
                   join details in dbTitleDetails on emps.EmpGuid equals details.EmpGuid
                   select new DTO.V_CheckXMFZR()
                   {
                       ID = emps.ID,
                       EmpGuid = emps.EmpGuid,
                       TypeFlag = emps.TypeFlag,
                       bGrade = users.RoleID,
                       CertificateLevel = details.CertificateLevel,
                       EmpName = emps.Name
                   };
        }

        /// <summary>
        /// 人员押证查询-获取人员信息--2013-5-14修改，人员押证在项目库中验证
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        public override string CheckXMFZR(string empId)
        {
            string result = string.Empty;
            Guid empGuid = Guid.Empty;
            int empIntId = 0;
            if (string.IsNullOrEmpty(empId))
            {
                result = "9,参数不能为空.";
                return JsonConvert.SerializeObject(result);
            }
            if (!Guid.TryParse(empId, out empGuid))
            {
                if (int.TryParse(empId, out empIntId))
                {
                    empGuid = GetXMFZRQuery().Where(p => p.ID == empIntId).Select(p => p.EmpGuid).FirstOrDefault();
                    if (empGuid == Guid.Empty)
                    {
                        result = "9,人员empGuid不能为空.";
                        return JsonConvert.SerializeObject(result);
                    }
                }
                else
                {
                    result = "9,传入的参数格式不正确.";
                    return JsonConvert.SerializeObject(result);
                }
            }
            ////1.获取人员信息
            DTO.V_CheckXMFZR manager = GetXMFZRQuery().Where(p => p.EmpGuid == empGuid).FirstOrDefault();
            if (manager != null)
            {
                string bGrade = "0";
                if (manager.bGrade != null)
                {
                    bGrade = manager.bGrade.ToString();
                }
                ////返回人员信息，作为项目库中查询押证的参数
                result = "0," + manager.ID + ":" + manager.TypeFlag + ":" + bGrade + ":" + manager.CertificateLevel;
            }
            else
            {
                result = "9,人员信息不存在或未通过审核请检查人员信息。";
            }

            return JsonConvert.SerializeObject(result);

        }
        /// <summary>
        /// 押证查询
        /// </summary>
        /// <param name="empId">ID或GUID</param>
        /// <param name="roleId">企业roleid</param>
        /// <returns></returns>
        public override string CheckXMFZR(string empId, string roleId, string areaCode)
        {
            string result = string.Empty;
            Guid empGuid = Guid.Empty;
            int empIntId = 0;
            if (string.IsNullOrEmpty(empId))
            {
                result = "9,参数不能为空.";
                return JsonConvert.SerializeObject(result);
            }
            ////值不为GUID
            if (!Guid.TryParse(empId, out empGuid))
            {
                if (int.TryParse(empId, out empIntId))
                {
                    empGuid = GetXMFZRQuery().Where(p => p.ID == empIntId).Select(p => p.EmpGuid).FirstOrDefault();
                    if (empGuid == Guid.Empty)
                    {
                        result = "9,人员empGuid不能为空.";
                        return JsonConvert.SerializeObject(result);
                    }
                }
                else
                {
                    result = "9,传入的参数格式不正确.";
                    return JsonConvert.SerializeObject(result);
                }
            }
            int bGrade = -1;
            if (!int.TryParse(roleId, out bGrade))
            {
                result = "9,传入的参数RoleId格式不正确.";
                return JsonConvert.SerializeObject(result);
            }
            ////按地区取得押证设置表数据
            var emp_ManagerCert = qdcontext.emp_ManagerCertCount.Where(e => e.RoleId == roleId && (!e.IsDel ?? true) && e.AreaCode == areaCode.Substring(0, 2)).OrderByDescending(e => e.SortCode);
            var TypeFlag = emp_ManagerCert.Select(m => m.TypeFlag).ToList();////押证人员类型
            IList<DTO.V_CheckXMFZR> managers = new List<DTO.V_CheckXMFZR>();
            ////取得人员信息
            managers = GetXMFZRQuery().Where(p => p.EmpGuid == empGuid && p.bGrade == bGrade && TypeFlag.Contains(p.TypeFlag ?? "-99")).ToList();
            if (managers == null)
            {
                result = "9,此人员可能存在以下问题：1.人员信息不存在或未审核通过 2.此人员没有项目负责人资格。";
                return JsonConvert.SerializeObject(result);
            }
            var empTypeFlag = managers.Select(m => m.TypeFlag);////人员类型
            var CertLevel = managers.Select(m => m.CertificateLevel);////证书等级
            ////取得押证数量
            int CertCount = emp_ManagerCert.Where(e => empTypeFlag.Contains(e.TypeFlag) && (CertLevel.Contains(e.CertLevel) || e.CertLevel == "-99")).OrderByDescending(e => e.SortCode).Select(e => e.CertCount ?? 0).FirstOrDefault();
            if (CertCount > 0)
            {
                result = "0," + managers[0].ID + ":" + CertCount.ToString() + ":" + managers[0].EmpName;
            }
            else
            {
                result = "9,人员既不是监理企业项目总监也不是施工企业项目经理.";
            }
            return JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 判断企业和项目经理是否临时锁定
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="personId"></param>
        /// <returns></returns>
        public bool CheckTempLock(string areaCode, string objectId, int typeFlag)
        {

            Zb_TempLock_Qd templock = qdcontext.ZbTempLock.Where(t => t.AreaCode == areaCode && t.ObjectId == objectId && t.TypeFlag == typeFlag).FirstOrDefault();
            if (templock != null && templock.IsLocked == true)
            {
                return true;
            }
            return false;
        }

        ///// <summary>
        ///// 押证操作
        ///// </summary>
        ///// <param name="empId"></param>
        ///// <returns></returns>
        //public override bool EmpLockCertificate(
        //    string projectName,
        //    string ProjectKind,
        //    string CorpName,
        //    string xmjlName,
        //    string xmjlCode,
        //    string xmjlID,
        //    string areacode,
        //    string bidid,
        //    string zbkindclassid)
        //{
        //    int biaoduanid, kind, jingliid, classid;
        //    int.TryParse(bidid, out biaoduanid);
        //    int.TryParse(ProjectKind, out kind);
        //    int.TryParse(xmjlID, out jingliid);
        //    int.TryParse(zbkindclassid, out classid);
        //    zb_emp_LockCertificate empLock = new zb_emp_LockCertificate
        //    {
        //        areacode = areacode,
        //        bidid = biaoduanid,
        //        CorpName = CorpName,
        //        ProjectKind = kind,
        //        projectName = projectName,
        //        xmjlCode = xmjlCode,
        //        xmjlID = jingliid,
        //        xmjlName = xmjlName,
        //        zbkindclassid = classid,
        //        dateZB = DateTime.Now,
        //        editDate = DateTime.Now
        //    };
        //    bool isLock = false;
        //    int lockCount = 0;////可押证数
        //    try
        //    {
        //        ////取得项目负责人可押证数
        //        IList<DTO.V_CheckXMFZR> managers = qdcontext.CheckXMFZR.Where(p => p.ID == jingliid).OrderByDescending(p => p.bGrade).ToList();
        //        foreach (DTO.V_CheckXMFZR m in managers)
        //        {
        //            if (m.bGrade == 15 || m.bGrade == 17)////项目经理押一证
        //            {
        //                lockCount = 1;
        //                break;
        //            }
        //            if (m.bGrade == 42)////项目总监押三证
        //            {
        //                lockCount = 3;
        //                break;
        //            }
        //        }
        //        ////已押证数
        //        int listCount = qdcontext.LockCertificate.Where(p => p.xmjlID == jingliid && p.bidid == int.Parse(bidid) && p.bstatus == "1").Count();
        //        if (lockCount <= listCount)
        //        {
        //            return false;
        //        }
        //        ////押证
        //        ////添加zb_emp_LockCertificate
        //        empLock.bstatus = "1";
        //        empLock = qdcontext.LockCertificate.Add(empLock);
        //        qdcontext.SaveChanges();
        //        isLock = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        SysLogManager.Log(new Sys_Log()
        //        {
        //            ErrorMessage = ex.Message,
        //            LogDate = DateTime.Now
        //        });
        //    }
        //    return isLock;
        //}

        ///// <summary>
        ///// 解证操作
        ///// </summary>
        ///// <param name="xmjlID"></param>
        ///// <param name="bidid"></param>
        ///// <returns></returns>
        //public override bool EmpUnlockCertificate(int xmjlID, int bidid, string areaCode)
        //{
        //    bool isUnLock = false;
        //    try
        //    {
        //        ////修改zb_emp_LockCertificate
        //        ////查询数据库
        //        zb_emp_LockCertificate dbLockInfo = qdcontext.LockCertificate.Where(p => p.xmjlID == xmjlID && p.bidid == bidid && p.bstatus == "1").FirstOrDefault();
        //        ////修改赋值
        //        if (dbLockInfo != null)
        //        {
        //            dbLockInfo.bstatus = "0";
        //            dbLockInfo.editDate = DateTime.Now;
        //        }
        //        qdcontext.SaveChanges();
        //        isUnLock = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        SysLogManager.Log(new Sys_Log()
        //        {
        //            ErrorMessage = ex.Message,
        //            LogDate = DateTime.Now
        //        });
        //    }
        //    return isUnLock;
        //}
        #endregion

        #region 人员解锁、加锁 作者：
        /// <summary>
        /// 加锁
        /// </summary>
        /// <param name="id"></param>
        public override bool LockEmpManagerBCanBid(string empGuid, string areaCode)
        {
            bool returnValue = false;
            Guid eGuid = Guid.Empty;
            if (Guid.TryParse(empGuid, out eGuid))
            {
                tb_Emp_Manager currentManager = qdcontext.Emp_Manager.Where(p => p.EmpGuid == eGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                if (currentManager != null)
                {
                    try
                    {
                        ////修改人员加锁状态
                        ////bCanBid 含有1时，不可以招标 
                        if (string.IsNullOrEmpty(currentManager.bCanBid))
                        {
                            currentManager.bCanBid = "1";
                        }
                        else
                        {
                            if (!currentManager.bCanBid.Contains("1"))
                            {
                                currentManager.bCanBid += ",1";
                            }

                        }
                        qdcontext.SaveChanges();
                        ////记录日志
                        loghelper.InsertUserLog("修改人员加锁状态", empGuid, "8000", "2");
                        returnValue = true;
                    }
                    catch (Exception ex)
                    {
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });

                    }
                }
            }
            return returnValue;
        }

        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="id"></param>
        public override bool UnLockEmpManagerBCanBid(string empGuid, string areaCode)
        {
            bool returnValue = false;
            Guid eGuid = Guid.Empty;
            if (Guid.TryParse(empGuid, out eGuid))
            {
                tb_Emp_Manager currentManager = qdcontext.Emp_Manager.Where(p => p.EmpGuid == eGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                if (currentManager != null)
                {
                    try
                    {
                        ////修改人员加锁状态
                        ////bCanBid 不含有1时，可以招标 
                        if (!string.IsNullOrEmpty(currentManager.bCanBid))
                        {
                            if (currentManager.bCanBid.Contains(",1"))
                            {
                                currentManager.bCanBid = currentManager.bCanBid.Replace(",1", "");
                            }
                            else
                                if (currentManager.bCanBid.Contains("1,"))
                                {
                                    currentManager.bCanBid = currentManager.bCanBid.Replace("1,", "");
                                }
                                else
                                    if (currentManager.bCanBid.Contains("1"))
                                    {
                                        currentManager.bCanBid = currentManager.bCanBid.Replace("1", "");
                                    }

                            qdcontext.SaveChanges();
                            ////记录日志
                            loghelper.InsertUserLog("修改人员加锁状态", empGuid, "8000", "2");
                        }
                        returnValue = true;
                    }
                    catch (Exception ex)
                    {
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });

                    }
                }
            }
            return returnValue;
        }
        #endregion

        #region 人员业绩
        /// <summary>
        /// 获取人员业绩列表
        /// </summary>
        /// <param name="typeFlag"></param>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override IList<DTO.e_OuterPrize> GetManager_e_OuterPrize(string empGuid, int pageIndex, int pageSize, string areaCode)
        {
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out cGuid))
            {
                return null;
            }
            var eouterprize = qdcontext.e_Outerprize.Where(e => e.EmpGuid == cGuid).ToList().OrderByDescending(m => m.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            List<DTO.e_OuterPrize> list_D = new List<DTO.e_OuterPrize>();
            foreach (e_OuterPrize item in eouterprize)
            {
                DTO.e_OuterPrize emp_D = new DTO.e_OuterPrize();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        public override int GetManager_e_OuterPrizeCount(string empGuid, string areaCode)
        {
            Guid cGuid = Guid.Empty;
            if (!Guid.TryParse(empGuid, out cGuid))
            {
                return 0;
            }
            int eouterprizecount = qdcontext.e_Outerprize.Where(e => e.EmpGuid == cGuid).ToList().Count;

            return eouterprizecount;
        }
        #endregion

        #region 主管处罚登记

        public override IList<DTO.v_e_DeDuck> GetPunishmentList(int dogid, string strwhere, int pageIndex, int pageSize, out int count, string areaCode)
        {
            string strwheresql = "  where classid=2560 and (areacode like '02%' or Authorid = '" + dogid + "') ";
            if (!string.IsNullOrEmpty(strwhere))
            {
                strwheresql += strwhere;
            }
            string sql = "select *,CorpUserGuid as ID_guid from v_e_DeDuck ";
            sql = sql + strwheresql + " order by registerDate desc";

            var punishmentlist = qdcontext.Database.SqlQuery<v_e_DeDuck>(sql).ToList().OrderByDescending(m => m.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            count = qdcontext.Database.SqlQuery<v_e_DeDuck>(sql).ToList().Count;
            List<DTO.v_e_DeDuck> list_D = new List<DTO.v_e_DeDuck>();
            foreach (v_e_DeDuck item in punishmentlist)
            {
                DTO.v_e_DeDuck emp_D = new DTO.v_e_DeDuck();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        public override DTO.v_e_DeDuck GetDeDuck(int id, int itemid, string areaCode)
        {
            DTO.v_e_DeDuck educk = new DTO.v_e_DeDuck();
            v_e_DeDuck model = new v_e_DeDuck();
            model = qdcontext.Punishment.Where(e => e.ID == id && e.itemID == itemid).FirstOrDefault();
            EntityHelper.ConvertEntity2OtherEntity(model, educk);
            return educk;
        }

        public override IList<DTO.e_PrizeFlag> GetPrizeFlag(string areaCode)
        {
            var prizeflaglist = qdcontext.PrizeFlag.Where(p => p.bflag == 0).ToList();

            List<DTO.e_PrizeFlag> list_D = new List<DTO.e_PrizeFlag>();
            foreach (e_PrizeFlag item in prizeflaglist)
            {
                DTO.e_PrizeFlag emp_D = new DTO.e_PrizeFlag();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        #endregion

        #region 人员转入转出

        /// <summary>
        /// 人员转出
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public override DTO.OperationResult PersonToExit(string corpUserGuid, IList<string> emps, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            string exitFlowCode = string.Empty;
            int exitFlowCodeId = 0;
            var tsysuser = GetSysUserInfo(corpUserGuid);
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var empGuidItem in emps)
                    {
                        string csid = string.Empty;
                        Guid empguid = new Guid(empGuidItem);
                        var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == empguid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                        if (dbEmp != null)
                        {
                            if (dbEmp.IsExit == true)
                            {
                                result.Result = false;
                                result.Message = string.Format("所选人员：{0} 已被转出，无需再次操作。", dbEmp.Name);
                                return result;
                            }
                            else
                            {
                                ////注：此处查询IsDel == false ，当转出审核通过后会将IsDel=true 意义并不是删除，而是做个标识
                                var dbChangeSetExit = qdcontext.ChangeSetRecords.Where(p => p.ObjectId == empGuidItem && p.IsrtUserId == corpUserGuid && p.ObjectType == "9" && p.IsDel == false).OrderByDescending(m => m.Id).FirstOrDefault();
                                if (dbChangeSetExit != null)
                                {
                                    csid = dbChangeSetExit.ObjectName;
                                    string seid = dbChangeSetExit.Id.ToString();
                                    var ExitFlowCode = qdcontext.FlowCodes.Where(f => f.ObjectId == seid && f.CodeType == 8009).OrderByDescending(fo => fo.UpdateTime).FirstOrDefault();
                                    if (ExitFlowCode != null && !string.IsNullOrEmpty(ExitFlowCode.FlowCode))
                                    {
                                        exitFlowCode = ExitFlowCode.FlowCode;
                                        exitFlowCodeId = ExitFlowCode.Id;
                                        if ((exitFlowCode.StartsWith("0,019,") && !exitFlowCode.Contains("021,")) || exitFlowCode.StartsWith("1,019,029,"))
                                        {
                                            result.Result = false;
                                            result.Message = string.Format("所选人员：{0} 已转出上报，请等待主管审核，无需再次操作。", dbEmp.Name);
                                            return result;
                                        }
                                    }
                                }
                            }
                            ////设置人员转出状态为已转出（待接收）
                            //dbEmp.IsExit = true; //这一步等审核通过时修改

                            if (exitFlowCode.StartsWith("0,019,021,")) ////主管退回
                            {
                                var ExitFlowCode = qdcontext.FlowCodes.Where(f => f.Id == exitFlowCodeId && f.CodeType == 8009).FirstOrDefault();
                                ExitFlowCode.FlowCode = "0,019,022,";
                                qdcontext.SaveChanges();
                                ////记录详细日志
                                loghelper.InsertDetailUserLog("企业基本人员转出再次上报", csid, "8008", "1", log);
                            }
                            else
                            {
                                ////同时向Tb_ChangeSetRecord  Tb_ChangeRecord 插入转入与转出信息
                                DateTime optDate = DateTime.Now;
                                //1.插入变更集合表
                                Tb_ChangeSetRecord changeSet = new Tb_ChangeSetRecord()
                                {
                                    ObjectId = empGuidItem,
                                    Description = "企业人员转入",
                                    ObjectType = "8",
                                    ObjectName = dbEmp.Name,
                                    IsrtUserName = log.IsrtUserName,
                                    IsrtUserId = corpUserGuid,
                                    IsrtDate = optDate,
                                    IsDel = false
                                };
                                changeSet = qdcontext.ChangeSetRecords.Add(changeSet);
                                qdcontext.SaveChanges();

                                //2.插入变更详细信息表
                                Tb_ChangeRecord changeRec = new Tb_ChangeRecord()
                                {
                                    ClassID = 8008,
                                    ClassValue = 2,
                                    ChangeItem = "ChangeCorp",
                                    ChangeItemName = "企业人员转入",
                                    ChangeSetId = changeSet.Id,
                                    EmpGuid = empguid,
                                    BeforeChange = tsysuser.Name,
                                    BeforeValue = corpUserGuid,
                                    AfterChange = string.Empty,
                                    AfterValue = string.Empty,
                                    Remark = "企业人员转入",
                                    OptDate = optDate
                                };
                                qdcontext.ChangeRecords.Add(changeRec);
                                qdcontext.SaveChanges();

                                ////记录转出审核状态。
                                ////////////////////////////////////////////////////////////////
                                Tb_ChangeSetRecord changeSetExit = new Tb_ChangeSetRecord()
                                {
                                    ObjectId = empGuidItem,
                                    Description = "企业人员转出",
                                    ObjectType = "9",
                                    ObjectName = changeSet.Id.ToString(), ////借助此字段记录转入ID
                                    IsrtUserName = log.IsrtUserName,
                                    IsrtUserId = corpUserGuid,
                                    IsrtDate = optDate,
                                    IsDel = false
                                };
                                changeSetExit = qdcontext.ChangeSetRecords.Add(changeSetExit);
                                qdcontext.SaveChanges();

                                Tb_ChangeRecord changeRecExit = new Tb_ChangeRecord()
                                {
                                    ClassID = 8009,
                                    ClassValue = 2,
                                    ChangeItem = "ChangeCorp",
                                    ChangeItemName = "企业人员转出",
                                    ChangeSetId = changeSetExit.Id,
                                    EmpGuid = empguid,
                                    BeforeChange = tsysuser.Name,
                                    BeforeValue = corpUserGuid,
                                    AfterChange = string.Empty,
                                    AfterValue = string.Empty,
                                    Remark = "企业人员转出",
                                    OptDate = optDate
                                };
                                qdcontext.ChangeRecords.Add(changeRecExit);
                                qdcontext.SaveChanges();

                                Tb_FlowCode flowCode = new Tb_FlowCode()
                                {
                                    AreaCode = "02",
                                    FlowCode = "0,019,",
                                    CodeType = 8009,
                                    ObjectId = changeSetExit.Id.ToString(),
                                    UpdateTime = optDate,
                                    RoleId = log.IsrtUserRole,
                                    IsDel = false
                                };
                                qdcontext.FlowCodes.Add(flowCode);
                                qdcontext.SaveChanges();
                                /////////////////////////////////////////////////////////////////

                                ////记录详细日志  转入转出用同一个functionid 8008记录以确保转入与转出记录同时查看
                                loghelper.InsertDetailUserLog("企业基本人员转出上报", changeSet.Id.ToString(), "8008", "1", log);
                            }
                        }

                    }
                    tran.Commit();
                    result.Result = true;
                    result.Message = "人员转出上报成功,请等待主管审核。";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员转出失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }


        /// <summary>
        /// 人员转出主管审核
        /// </summary>
        /// <param name="changeSetIDs"></param>
        /// <param name="flowCode"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public override DTO.OperationResult PersonToExitAudit(List<string> changeSetIDs, string AuditFlowCode, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    if (changeSetIDs != null && changeSetIDs.Count > 0)
                    {
                        foreach (string changeSetID in changeSetIDs)
                        {
                            ////根据ChangeSetID与CodeType=8009获取最新一次的变更审核记录
                            var flowCode = qdcontext.FlowCodes.Where(f => f.ObjectId == changeSetID && f.CodeType == 8009).OrderByDescending(fo => fo.UpdateTime).FirstOrDefault();

                            int ecsid = 0;
                            int.TryParse(changeSetID, out ecsid);
                            var dbChangeSetExit = qdcontext.ChangeSetRecords.Where(p => p.Id == ecsid && p.ObjectType == "9").FirstOrDefault();

                            if (dbChangeSetExit != null && flowCode != null)
                            {
                                ////判断如果已通过或已退回就不再审核
                                if (flowCode.FlowCode.StartsWith("1") || flowCode.FlowCode.Contains(",021"))
                                {
                                    tran.Commit();
                                    result.Message = "该人员已被主管审核，无需再次审核";
                                    result.Result = false;
                                    return result;
                                }
                                else
                                {
                                    ////如果是审核通过
                                    if (AuditFlowCode.StartsWith("1,019,029"))
                                    {
                                        ////设置人员转出状态为已转出（待接收）
                                        Guid eGuid = Guid.Empty;
                                        if (Guid.TryParse(dbChangeSetExit.ObjectId, out eGuid))
                                        {
                                            var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == eGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();

                                            if (dbEmp != null)
                                            {
                                                dbChangeSetExit.IsDel = true;////同时标记IsDel
                                                dbEmp.IsExit = true;
                                            }
                                        }

                                    }

                                    flowCode.FlowCode = AuditFlowCode;
                                    flowCode.UpdateTime = DateTime.Now;
                                    qdcontext.SaveChanges();
                                    ////记录日志
                                    loghelper.InsertDetailUserLog("人员转出信息审核", dbChangeSetExit.ObjectName, "8008", "4", log);
                                }
                            }

                        }
                    }
                    tran.Commit();
                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "人员转出信息审核成功";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "审核人员转出信息失败" + ex.InnerException;
                    result.Result = false;
                }
            }
            return result;
        }

        /// <summary>
        /// 人员转入
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public override DTO.OperationResult PersonToEntry(string corpUserGuid, IList<string> changeSetIDs, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            var tsysuser = GetSysUserInfo(corpUserGuid);
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var changeSetID in changeSetIDs)
                    {
                        int csid = 0;
                        int.TryParse(changeSetID, out csid);
                        DateTime optDate = DateTime.Now;

                        var dbChangeSet = qdcontext.ChangeSetRecords.Where(p => p.Id == csid && p.ObjectType == "8" && (p.IsDel != true || p.IsDel == null)).OrderByDescending(m => m.Id).FirstOrDefault();
                        var dbChangeRec = qdcontext.ChangeRecords.Where(p => p.ChangeSetId == dbChangeSet.Id && p.ClassID == 8008).OrderByDescending(m => m.ID).FirstOrDefault();

                        Guid empguid = new Guid(dbChangeSet.ObjectId);
                        var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == empguid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();

                        if (dbEmp.IsExit == null || dbEmp.IsExit != true || !string.IsNullOrEmpty(dbChangeRec.AfterChange))
                        {
                            result.Result = false;
                            result.Message = string.Format("所选人员已被:{0} 转入，不可再次操作。", dbChangeRec.AfterChange);
                            return result;
                        }

                        ////录入接收公司的公司名与公司corpUserGuid
                        dbChangeRec.AfterChange = tsysuser.Name;
                        dbChangeRec.AfterValue = corpUserGuid;

                        ////记录审核状态。
                        Tb_FlowCode flowCode = new Tb_FlowCode()
                        {
                            AreaCode = "02",
                            FlowCode = "0",
                            CodeType = 8008,
                            ObjectId = dbChangeSet.Id.ToString(),
                            UpdateTime = optDate,
                            RoleId = log.IsrtUserRole,
                            IsDel = false
                        };
                        qdcontext.FlowCodes.Add(flowCode);
                        qdcontext.SaveChanges();

                        ////记录详细日志
                        loghelper.InsertDetailUserLog("企业基本人员转入", dbChangeSet.Id.ToString(), "8008", "1", log);

                    }
                    tran.Commit();
                    result.Result = true;
                    result.Message = "人员转入成功，请上报。";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员转入失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 人员转入上报
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <param name="emps">人员集合</param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override DTO.OperationResult PersonToPost(IList<string> changeSetIDs, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();

            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var changeSetID in changeSetIDs)
                    {
                        ////根据ChangeSetID与CodeType=8008获取最新一次的变更审核记录
                        var flowCode = GetPersonEntryExitOneChangeStatus(changeSetID);
                        int csid = 0;
                        int.TryParse(changeSetID, out csid);
                        var dbChangeSet = qdcontext.ChangeSetRecords.Where(p => p.Id == csid && p.ObjectType == "8" && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                        if (dbChangeSet != null && flowCode != null)
                        {
                            ////判断如果已上报就不再上报
                            if (flowCode.FlowCode.StartsWith("0,019") && !flowCode.FlowCode.Contains(",021"))
                            {
                                tran.Commit();
                                result.Message = "人员转入信息已上报，无需再次上报";
                                result.Result = false;
                                return result;
                            }
                            else
                            {
                                if (flowCode.FlowCode.StartsWith("0,019,021"))
                                {
                                    flowCode.FlowCode = "0,019,022,";
                                }
                                else
                                {
                                    flowCode.FlowCode = "0,019,";
                                }
                                flowCode.UpdateTime = DateTime.Now;
                                qdcontext.SaveChanges();
                                ////记录日志
                                loghelper.InsertDetailUserLog("人员转入信息上报", dbChangeSet.Id.ToString(), "8008", "4", log);
                            }
                        }
                    }

                    tran.Commit();
                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "人员转入信息上报成功";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "人员转入信息上报失败" + ex.InnerException;
                    result.Result = false;
                }
            }

            return result;
        }

        /// <summary>
        /// 人员转入主管审核
        /// </summary>
        /// <param name="changeSetIDs"></param>
        /// <param name="flowCode"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public override DTO.OperationResult PersonToAudit(List<string> changeSetIDs, string AuditFlowCode, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    if (changeSetIDs != null && changeSetIDs.Count > 0)
                    {
                        foreach (string changeSetID in changeSetIDs)
                        {
                            ////根据ChangeSetID与CodeType=8008获取最新一次的变更审核记录
                            var flowCode = GetPersonEntryExitOneChangeStatus(changeSetID);
                            int csid = 0;
                            int.TryParse(changeSetID, out csid);
                            var dbChangeSet = qdcontext.ChangeSetRecords.Where(p => p.Id == csid && p.ObjectType == "8" && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                            if (dbChangeSet != null && flowCode != null)
                            {
                                ////判断如果已通过或已退回就不再审核
                                if (flowCode.FlowCode.StartsWith("1") || flowCode.FlowCode.Contains(",021"))
                                {
                                    tran.Commit();
                                    result.Message = "该人员已被主管审核，无需再次审核";
                                    result.Result = false;
                                    return result;
                                }
                                else
                                {
                                    ////如果是审核通过
                                    if (AuditFlowCode.StartsWith("1,019,029"))
                                    {
                                        ////修改基本人员信息tb_Emp_Manager表CorpGuid、DogID与IsExit字段
                                        Guid eGuid = Guid.Empty;
                                        if (Guid.TryParse(dbChangeSet.ObjectId, out eGuid))
                                        {
                                            var dbChangeRec = qdcontext.ChangeRecords.Where(p => p.EmpGuid == eGuid && p.ClassID == 8008 && p.ChangeSetId == dbChangeSet.Id).OrderByDescending(m => m.ID).FirstOrDefault();
                                            var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == eGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                                            ////查询接收公司信息
                                            Guid NewCorpGuid = new Guid(dbChangeRec.AfterValue);
                                            var corpinfo = qdcontext.Corp_CompanyInfos.Where(f => f.CorpUserGuid == NewCorpGuid && (f.IsDel != true || f.IsDel == null)).FirstOrDefault();

                                            if (dbChangeRec != null && dbEmp != null && corpinfo != null)
                                            {
                                                dbEmp.CorpGuid = NewCorpGuid;
                                                dbEmp.DogID = corpinfo.dogid;
                                                dbEmp.CorpID = corpinfo.ID.ToString();
                                                dbEmp.corpName = corpinfo.CorpName;
                                                dbEmp.IsExit = false;
                                            }

                                        }

                                    }

                                    flowCode.FlowCode = AuditFlowCode;
                                    flowCode.UpdateTime = DateTime.Now;
                                    qdcontext.SaveChanges();
                                    ////记录日志
                                    loghelper.InsertDetailUserLog("人员转入信息审核", dbChangeSet.Id.ToString(), "8008", "4", log);
                                }
                            }

                        }
                    }
                    tran.Commit();
                    result.Result = true;
                    result.ReturnValue = null;
                    result.Message = "人员转入信息审核成功";
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "审核人员转入信息失败" + ex.InnerException;
                    result.Result = false;
                }
            }
            return result;
        }

        /// <summary>
        /// 删除未上报或已退回的人员转入信息
        /// </summary>
        /// <param name="changeSetIDs"></param>
        /// <param name="flowCode"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public override DTO.OperationResult PersonToDel(List<string> changeSetIDs, User_Log log, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (var changeSetID in changeSetIDs)
                    {
                        ////根据ChangeSetID与CodeType=8008获取最新一次的变更审核记录
                        var flowCode = GetPersonEntryExitOneChangeStatus(changeSetID);
                        int csid = 0;
                        int.TryParse(changeSetID, out csid);
                        var dbChangeSet = qdcontext.ChangeSetRecords.Where(p => p.Id == csid && p.ObjectType == "8" && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();
                        if (dbChangeSet != null && flowCode != null)
                        {
                            ////判断如果已上报或审核通过的人员不可删除
                            if ((flowCode.FlowCode.StartsWith("1") || flowCode.FlowCode.StartsWith("0,019")) && !flowCode.FlowCode.Contains(",021"))
                            {
                                tran.Commit();
                                result.Message = "已上报或审核通过的人员不可删除！";
                                result.Result = false;
                                result.ReturnValue = null;
                                return result;
                            }

                            ////1.修改 Tb_ChangeRecord
                            Guid eGuid = Guid.Empty;
                            if (Guid.TryParse(dbChangeSet.ObjectId, out eGuid))
                            {
                                var dbChangeRec = qdcontext.ChangeRecords.Where(p => p.EmpGuid == eGuid && p.ClassID == 8008 && p.ChangeSetId == dbChangeSet.Id).FirstOrDefault();

                                if (dbChangeRec != null)
                                {
                                    ////清空接收公司信息
                                    dbChangeRec.AfterChange = string.Empty;
                                    dbChangeRec.AfterValue = string.Empty;

                                    ////2.删除 Tb_FlowCode
                                    flowCode.IsDel = true;
                                    flowCode.UpdateTime = DateTime.Now;
                                    qdcontext.SaveChanges();
                                    ////记录日志
                                    loghelper.InsertDetailUserLog("人员转入信息删除", dbChangeSet.Id.ToString(), "8008", "3", log);
                                }
                            }
                        }
                    }
                    tran.Commit();
                    result.Message = "删除成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "删除失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        /// <summary>
        /// 根据changeSetID查询关联人员信息
        /// </summary>
        /// <param name="setID"></param>
        /// <returns></returns>
        public override string GetEmpGuidBySetID(string setID, string areaCode)
        {
            string returnValue = Guid.Empty.ToString();
            int thisCsid = 0;
            int.TryParse(setID, out thisCsid);

            var dbDetails =
                from cs in qdcontext.ChangeSetRecords
                join cr in qdcontext.ChangeRecords on cs.Id equals cr.ChangeSetId
                into leftsrr
                from srr in leftsrr.DefaultIfEmpty()

                join emp in qdcontext.Emp_Manager on srr.EmpGuid equals emp.EmpGuid
                into leftsrremp
                from srremp in leftsrremp.DefaultIfEmpty()

                join tsys in qdcontext.T_Sys_Users on srremp.CorpGuid equals tsys.UserGuid
                into leftsysemp
                from sysemp in leftsysemp.DefaultIfEmpty()

                select new
                {
                    cs.Id,
                    cs.ObjectType,
                    cs.IsDel,
                    srr.ClassID,
                    srr.AfterValue,
                    srremp.IsExit,
                    empdel = srremp.IsDel,
                    srremp.EmpGuid
                };

            var dbDetail = dbDetails.Where(q => q.Id == thisCsid && q.ObjectType == "8" && q.IsDel == false && q.ClassID == 8008 && (q.empdel == false || q.empdel == null)).FirstOrDefault();
            if (dbDetail != null && dbDetail.EmpGuid != null)
            {
                returnValue = dbDetail.EmpGuid.ToString();
            }
            return returnValue;
        }

        /// <summary>
        /// 查询转入接收人员列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public override IList<DTO.V_PersonToEntryList> GetPersonToEntryList(string condition, int pageIndex, int pageSize, out int count, string areaCode)
        {
            if (StringHelper.SqlFilter(condition))
            {
                count = 0;
                return null;
            }
            var dbPersonToEntryList = new PersonDAL().GetAdminPersonToEntryList(condition, pageIndex, pageSize, out count);
            List<DTO.V_PersonToEntryList> list_D = new List<DTO.V_PersonToEntryList>();
            foreach (V_PersonToEntryList item in dbPersonToEntryList)
            {
                DTO.V_PersonToEntryList emp_D = new DTO.V_PersonToEntryList();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        /// <summary>
        /// 查询转出人员列表
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public override IList<DTO.V_PersonToEntryList> GetPersonToExitList(string condition, int pageIndex, int pageSize, out int count, string areaCode)
        {
            if (StringHelper.SqlFilter(condition))
            {
                count = 0;
                return null;
            }
            var dbPersonToEntryList = new PersonDAL().GetAdminPersonToExitList(condition, pageIndex, pageSize, out count);
            List<DTO.V_PersonToEntryList> list_D = new List<DTO.V_PersonToEntryList>();
            foreach (V_PersonToEntryList item in dbPersonToEntryList)
            {
                DTO.V_PersonToEntryList emp_D = new DTO.V_PersonToEntryList();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        /// <summary>
        /// 获取企业下的需转出员工信息列表
        /// </summary>
        /// <param name="corpUserGuid">企业Guid</param>
        /// <param name="condition">sql where</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageSize">条数</param>
        /// <returns></returns>
        public override string GetPersonWantToExit(string corpUserGuid, string condition, int pageIndex, int pageSize, out int count, string areaCode)
        {
            count = 0;
            var list = new List<tb_Emp_Manager1>();

            if (!string.IsNullOrEmpty(corpUserGuid))
            {
                if (!StringHelper.SqlFilter(condition))
                {
                    list = new PersonDAL().GetPersonWantToExit(corpUserGuid, condition, pageIndex, pageSize, out  count);
                }
            }

            return JsonConvert.SerializeObject(list);
        }


        /// <summary>
        /// 获取待转区信息列表
        /// </summary>
        /// <param name="condition">sql where</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageSize">条数</param>
        /// <returns></returns>
        public override string GetPersonToWaitArea(string condition, int pageIndex, int pageSize, out int count, string areaCode)
        {
            count = 0;
            var list = new List<V_PersonToEntryList>();
            if (!StringHelper.SqlFilter(condition))
            {
                list = new PersonDAL().GetPersonToWaitArea(condition, pageIndex, pageSize, out  count);
            }

            return JsonConvert.SerializeObject(list);
        }

        /// <summary>
        /// 查询人员转出审核状态
        /// </summary>
        /// <returns></returns>
        public override string GetFlowCodeExit(string corpUserGuid, string empGuid, string areaCode)
        {
            string returnValue = "0";
            var dbChangeSetExit = qdcontext.ChangeSetRecords.Where(p => p.ObjectId == empGuid && p.IsrtUserId == corpUserGuid && p.ObjectType == "9").OrderByDescending(m => m.Id).FirstOrDefault();
            if (dbChangeSetExit != null)
            {
                string seid = dbChangeSetExit.Id.ToString();
                var ExitFlowCode = qdcontext.FlowCodes.Where(f => f.ObjectId == seid && f.CodeType == 8009).OrderByDescending(fo => fo.UpdateTime).FirstOrDefault();
                if (ExitFlowCode != null && !string.IsNullOrEmpty(ExitFlowCode.FlowCode))
                {
                    returnValue = ExitFlowCode.FlowCode;
                    if (dbChangeSetExit.IsDel == true && ExitFlowCode.FlowCode.StartsWith("1"))
                    {
                        Guid eGuid = new Guid(empGuid);

                        var dbEmp = qdcontext.Emp_Manager.Where(p => p.EmpGuid == eGuid && (p.IsDel != true || p.IsDel == null)).FirstOrDefault();

                        if (dbEmp.IsExit == false)
                        {
                            returnValue = "0";
                        }
                    }
                }
            }
            return returnValue;
        }

        /// <summary>
        /// 获取empGuid 与 log的objectid
        /// </summary>
        /// <param name="setId"></param>
        /// <returns></returns>
        public override string GetPersonExitLogId(string setId, string corpUserGuid, string empGuid, string areaCode)
        {
            string returnValue = string.Empty;
            if (!string.IsNullOrEmpty(setId))
            {
                int csid = 0;
                int.TryParse(setId, out csid);
                var dbChangeSetExit = qdcontext.ChangeSetRecords.Where(p => p.Id == csid).FirstOrDefault();
                returnValue = dbChangeSetExit.ObjectId + "," + dbChangeSetExit.ObjectName;
            }
            else
            {
                var dbChangeSetExit = qdcontext.ChangeSetRecords.Where(p => p.ObjectId == empGuid && p.IsrtUserId == corpUserGuid && p.ObjectType == "9").OrderByDescending(m => m.Id).FirstOrDefault();
                if (dbChangeSetExit != null)
                {
                    returnValue = dbChangeSetExit.ObjectName;
                }
            }
            return returnValue;
        }

        #endregion

        #region 是否是项目主管
        public override bool CheckEmp(string empguid, string areaCode)
        {
            Guid EmpGuid = Guid.Empty;
            if (!Guid.TryParse(empguid, out EmpGuid))
            {
                return false;
            }
            var manager = qdcontext.Emp_Manager.Where(e => e.EmpGuid == EmpGuid).FirstOrDefault();
            if (manager != null)
            {
                if (manager.TypeFlag == "100")
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 获取人员及资质信息
        public override IList<DTO.ManagerInfoDL> GetManagerInfoForDL(string DogID, string areaCode)
        {
            var dbEmpManager = qdcontext.Emp_Manager;
            var dbTitleDetail = qdcontext.Emp_Qualities;
            string[] typeflaglist = { "100", "101", "103" };
            int dogid = Convert.ToInt32(DogID);
            var query = from e in dbEmpManager
                        join t in dbTitleDetail
                        on e.EmpGuid equals t.EmpGuid
                        into managerinfo
                        from manager in managerinfo.DefaultIfEmpty()
                        where typeflaglist.Contains(e.TypeFlag) && e.empdogid == dogid

                        select new DTO.ManagerInfoDL
                        {
                            ID = e.ID,
                            empdogid = (int)e.empdogid,
                            Name = e.Name,
                            TypeFlag = e.TypeFlag,
                            CertificateCode = manager.CertificateCode,
                            CertificateName = manager.CSCode + manager.CertificateName,
                            CertificateLevel = manager.CertificateLevel
                        };

            if (query != null)
            {
                return query.ToList();
            }
            return null;
        }
        #endregion

        #region 公告模块
        public override DTO.OperationResult NoticeAdd(DTO.Notice notice, List<string> entityguidlist, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            try
            {
                Notice notice1 = new Notice();
                EntityHelper.ConvertEntity2OtherEntity(notice, notice1);
                notice1.IsDel = false;
                notice1.AppId = 1;
                qdcontext.Notice.Add(notice1);

                if (entityguidlist != null && entityguidlist.Count > 0)
                {
                    foreach (string entityguid in entityguidlist)
                    {
                        if (entityguid != "")
                        {
                            Guid notguid = notice.NotGuid == null ? Guid.Empty : new Guid(notice.NotGuid.ToString());
                            Guid entityGuid = new Guid(entityguid);
                            //var noticeextist = qdcontext.receiveNotice.Where(n => n.NotGuid == notguid && n.EntityGuid == entityGuid);
                            //if (noticeextist == null)
                            //{
                            ReceiveNotice receivenotice = new ReceiveNotice();
                            receivenotice.NotGuid = notguid;
                            receivenotice.EntityGuid = entityGuid;
                            qdcontext.receiveNotice.Add(receivenotice);
                            //}
                        }
                    }
                }
                if (qdcontext.SaveChanges() > 0)
                {
                    result.Message = "公告添加成功";
                    result.Result = true;
                }
            }
            catch (Exception)
            {
                result.Message = "公告添加失败";
                result.Result = true;
            }
            return result;
        }

        public override DTO.OperationResult NoticeEdit(IList<DTO.Notice> noticeinfolist, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (DTO.Notice noticeinfo in noticeinfolist)
                    {
                        Notice notice = qdcontext.Notice.Where(n => n.Id == noticeinfo.Id).FirstOrDefault();
                        if (notice != null)
                        {
                            if (!string.IsNullOrEmpty(noticeinfo.Title))
                            {
                                notice.Title = noticeinfo.Title;
                            }
                            if (!string.IsNullOrEmpty(noticeinfo.Content))
                            {
                                notice.Content = noticeinfo.Content;
                            }
                            if (noticeinfo.PublishTime != null)
                            {
                                notice.PublishTime = noticeinfo.PublishTime;
                            }
                            if (noticeinfo.PublistPerson != null)
                            {
                                notice.PublistPerson = noticeinfo.PublistPerson;
                            }
                            if (noticeinfo.IsIssue != null)
                            {
                                notice.IsIssue = noticeinfo.IsIssue;
                            }
                            notice.Id = noticeinfo.Id;
                            qdcontext.SaveChanges();
                        }
                    }

                    result.Message = "修改公告成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "修改公告失败：" + ex.Message;
                    result.Result = false;
                }
            }
            return result;
        }

        public override DTO.OperationResult NoticeDelete(IList<string> idlist, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    foreach (string idstr in idlist)
                    {
                        int id = Convert.ToInt32(idstr);
                        var notice = qdcontext.Notice.Where(n => n.Id == id).FirstOrDefault();
                        if (notice != null)
                        {
                            notice.IsDel = true;
                            qdcontext.SaveChanges();
                        }
                    }
                    tran.Commit();
                    result.Message = "删除成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "删除失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }

        public override DTO.Notice GetNoticeInfo(int id, string areaCode)
        {
            Notice notice = qdcontext.Notice.Where(n => n.Id == id).FirstOrDefault();
            DTO.Notice notice1 = new DTO.Notice();
            EntityHelper.ConvertEntity2OtherEntity(notice, notice1);
            return notice1;
        }

        public override IList<DTO.Notice> GetAllNotice(DTO.Notice noticeinfo, string logintype, string entityguid, string areaCode)
        {
            List<DTO.Notice> noticelist1 = new List<DTO.Notice>();
            List<Notice> noticelist = new List<Notice>();

            if (logintype.ToLower() == "corp")
            {
                DbSet<Notice> newnoticelist = qdcontext.Notice;
                DbSet<ReceiveNotice> receivelist = qdcontext.receiveNotice;

                Guid entityGuid = new Guid(entityguid);
                var query = from n in newnoticelist
                            join r in receivelist
                            on n.NotGuid equals r.NotGuid
                            where r.EntityGuid == entityGuid
                            && n.IsDel == false && n.IsIssue == true && n.AppId == 1
                            orderby n.PublishTime descending
                            select n;
                noticelist = query.ToList<Notice>().Distinct().ToList<Notice>();
            }
            else
            {
                noticelist = qdcontext.Notice.Where(n => n.Id > 0 && n.IsDel == false && n.AppId == 1).OrderByDescending(n => n.PublishTime).ToList();
            }
            if (noticeinfo != null)
            {
                if (noticeinfo.Title != null)
                {
                    noticelist = noticelist.Where(n => n.Title.Contains(noticeinfo.Title) && n.AppId == 1).ToList();
                }
            }
            if (noticelist != null)
            {
                foreach (Notice notice in noticelist)
                {
                    DTO.Notice notice1 = new DTO.Notice();
                    EntityHelper.ConvertEntity2OtherEntity(notice, notice1);
                    noticelist1.Add(notice1);
                }
            }
            return noticelist1;
        }

        public override DTO.OperationResult AddViewCount(int id, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)base.baseContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    Notice notice = qdcontext.Notice.Where(n => n.Id == id).FirstOrDefault();
                    if (notice != null)
                    {
                        notice.ViewCount = notice.ViewCount + 1;
                    }
                    qdcontext.SaveChanges();
                    tran.Commit();
                    result.Message = "成功！";
                    result.Result = true;
                    result.ReturnValue = null;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "失败：" + ex.Message;
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            return result;
        }
        #endregion

        public override string GetManagerByZbdlDogid(int dogid)
        {
            var qdEmps = qdcontext.Emp_Manager;
            var qdDetails = qdcontext.Emp_Qualities;
            var query = from qdEmp in qdEmps
                        join qdDetail in qdDetails on qdEmp.EmpGuid equals qdDetail.EmpGuid
                        into empDetails
                        from empDetail in empDetails.DefaultIfEmpty()
                        where qdEmp.empdogid == dogid
                        select new
                        {
                            Id = qdEmp.ID,
                            CertificateCode = empDetail.CertificateCode,
                            Name = qdEmp.Name,
                            TypeFlag = qdEmp.TypeFlag,
                            CsCode = empDetail.CSCode + empDetail.CertificateName,
                            ClCode = empDetail.CLCode
                        };
            return JsonConvert.SerializeObject(query.FirstOrDefault());
        }

        #region 工程类获奖相关人员服务
        public override List<string> GetPersonType(string empGuid, string areaCode)
        {
            Guid EmpGuid = new Guid();
            if (!Guid.TryParse(empGuid, out EmpGuid))
            {
                return null;
            }
            else
            {
                string sql = "select distinct(r.typename) from tb_emp_manager m inner join tb_emp_ManagerRole r on m.empguid=r.empguid where m.empguid='" + empGuid + "' ";
                return qdcontext.Database.SqlQuery<string>(sql).ToList();
            }
            return null;
        }

        public override IList<DTO.V_ManagerList> GetManagerListByCorpGuid(DTO.V_ManagerList conditon, string areaCode)
        {
            var query = qdcontext.V_ManagerList.Where(q => q.IsDel == conditon.IsDel);
            if (conditon != null)
            {
                if (!string.IsNullOrEmpty(conditon.corpName) || !string.IsNullOrEmpty(conditon.Name))
                {
                    query = query.Where(v => v.corpName.Contains(conditon.corpName.Trim()) || v.Name.Contains(conditon.corpName.Trim()));
                }
                if (conditon.CorpUserGuid != null)
                {
                    query = query.Where(q => q.CorpUserGuid == conditon.CorpUserGuid);
                }
                if (!string.IsNullOrEmpty(conditon.FlowCode))
                {
                    if (conditon.FlowCode == "1")
                    {
                        query = query.Where(q => q.FlowCode.StartsWith("1"));
                    }
                }
                if (!string.IsNullOrEmpty(conditon.TypeFlag))
                {
                    query = query.Where(q => conditon.type.Split(',').Contains(q.Type));
                }
            }

            List<DTO.V_ManagerList> list_D = new List<DTO.V_ManagerList>();
            foreach (V_ManagerList item in query.ToList())
            {
                DTO.V_ManagerList emp_D = new DTO.V_ManagerList();
                EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
                list_D.Add(emp_D);
            }
            return list_D;
        }

        //public override IList<DTO.V_ManagerAndTitleCode> GetXMZJListByCorpGuid(string corpname, string pa, string areaCode)
        //{
        //    IList<V_ManagerList> query = qdcontext.V_ManagerAndTitleCode.Where(v => v.FlowCode.StartsWith("1") && v.TypeFlag == "2" && (v.corpName.Contains(corpname.Trim()) || v.Name.Contains(corpname.Trim()))).ToList();
        //    List<DTO.V_ManagerAndTitleCode> list_D = new List<DTO.V_ManagerAndTitleCode>();
        //    foreach (V_ManagerList item in query)
        //    {
        //        DTO.V_ManagerAndTitleCode emp_D = new DTO.V_ManagerAndTitleCode();
        //        EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
        //        list_D.Add(emp_D);
        //    }
        //    return list_D;
        //}

        //public override IList<DTO.V_ManagerAndTitleCode> GetZjListByPersonName(string corpid, string corpname, string pa, string areaCode)
        //{
        //    var query = qdcontext.V_ManagerAndTitleCode.Where(v => 1 == 1);
        //    int corpID = Convert.ToInt32(corpid);
        //    if (!string.IsNullOrEmpty(corpid) && !corpid.Equals("0"))
        //    {
        //        query = query.Where(q => q.CorpID == corpID);

        //    }
        //    if (!string.IsNullOrEmpty(corpname))
        //    {
        //        query = query.Where(q => q.corpName.Contains(corpname.Trim()) || q.Name.Contains(corpname.Trim()));
        //    }

        //    List<DTO.V_ManagerAndTitleCode> list_D = new List<DTO.V_ManagerAndTitleCode>();
        //    foreach (V_ManagerList item in query.Distinct().ToList())
        //    {
        //        DTO.V_ManagerAndTitleCode emp_D = new DTO.V_ManagerAndTitleCode();
        //        EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
        //        list_D.Add(emp_D);
        //    }
        //    return list_D;
        //}

        //public override IList<DTO.V_ManagerAndTitleCode> GetZbDlManagerByCondition(string corpname, string areacode)
        //{
        //    IList<V_ManagerList> query = qdcontext.V_ManagerAndTitleCode.Where(v => (v.TypeFlag == "100" || v.TypeFlag == "101") && v.corpName.Contains(corpname.Trim())).ToList();

        //    List<DTO.V_ManagerAndTitleCode> list_D = new List<DTO.V_ManagerAndTitleCode>();
        //    foreach (V_ManagerList item in query.Distinct().ToList())
        //    {
        //        DTO.V_ManagerAndTitleCode emp_D = new DTO.V_ManagerAndTitleCode();
        //        EntityHelper.ConvertEntity2OtherEntity(item, emp_D);
        //        list_D.Add(emp_D);
        //    }
        //    return list_D;
        //}

        public override IList<DTO.tb_Emp_Manager> GetEmpListByCorpID(string strWhere, string areacode)
        {
            List<DTO.tb_Emp_Manager> managerlist1 = new List<DTO.tb_Emp_Manager>();

            System.Text.StringBuilder strSql = new StringBuilder();
            strSql.Append("select t1.*,t3.CertificateCode,t3.CertificateName,t3.CLCode,t3.typeflags,t2.ID as corpid from tb_Emp_Manager t1 ");
            strSql.Append(" inner join tb_corp_companyinfo t2 on t1.CorpGuid = t2.CorpUserGuid ");
            strSql.Append(" left join tb_Emp_TitleDetails t3 on t1.EmpGuid = t3.EmpGuid  ");
            strSql.Append(" where t1.flowcode like '1%' and t1.IsDel<>1 and (t2.flowcode like '1%' or t2.bcanbid like '%3%') and t3.typeflags in (1,0,2) ");
            if (strWhere != "")
            {
                strSql.Append(strWhere);
            }
            System.Data.SqlClient.SqlParameter[] paramers = { };
            IList<tb_Emp_Manager> managerlist = qdcontext.Database.SqlQuery<tb_Emp_Manager>(strSql.ToString(), paramers).ToList();
            if (managerlist != null)
            {
                foreach (tb_Emp_Manager notice in managerlist)
                {
                    DTO.tb_Emp_Manager notice1 = new DTO.tb_Emp_Manager();
                    EntityHelper.ConvertEntity2OtherEntity(notice, notice1);
                    managerlist1.Add(notice1);
                }
            }
            return managerlist1;
        }
        #endregion

        #region 青岛招标代理系统首页人员信息统计
        public override IList<PersonStatisModel> PersonStatis(int roleid, string areacode)
        {
            var manager = qdcontext.Emp_Manager;
            var users = qdcontext.T_Sys_Users;
            var query = from m in manager
                        join u in users on new { CorpGuid = (Guid)m.CorpGuid } equals new { CorpGuid = u.UserGuid } into u_join
                        from u in u_join.DefaultIfEmpty()
                        where
                          (u.RoleID == 105 || u.RoleID == 99105) &&
                          u.DogID > 0 &&
                          (new string[] { "100", "101", "103" }).Contains(m.TypeFlag) &&
                          (m.IsDel == false ||
                          m.IsDel == null) &&
                          m.FlowCode.StartsWith("1,")
                        group m by new
                        {
                            m.TypeFlag
                        } into g
                        select new PersonStatisModel
                        {
                            Count = (Int32?)g.Count(),
                            TypeFlag = g.Key.TypeFlag,
                            TypeFlagName = g.Key.TypeFlag == "100" ? "项目主管" : g.Key.TypeFlag == "101" ? "项目经办人" : g.Key.TypeFlag == "103" ? "其他招标代理人员" : null
                        };
            IList<PersonStatisModel> lists = query.ToList<PersonStatisModel>();
            return lists;
        }

        public override IList<ManagerModel> GetManagerListZBDL(string queryCondition, out int count, int pageIndex, int pageSize, string areaCode)
        {
            ManagerModel managermodel = JsonConvert.DeserializeObject<ManagerModel>(queryCondition);

            var manager = qdcontext.Emp_Manager;
            var users = qdcontext.T_Sys_Users;

            var query = from m in manager
                        join u in users on new { CorpGuid = (Guid)m.CorpGuid } equals new { CorpGuid = u.UserGuid } into u_join
                        from u in u_join.DefaultIfEmpty()
                        where
                          (u.RoleID == 105 || u.RoleID == 99105) &&
                          u.DogID > 0 &&
                          (new string[] { "100", "101", "103" }).Contains(m.TypeFlag) &&
                          (m.IsDel == false ||
                          m.IsDel == null) &&
                          m.FlowCode.StartsWith("1,")
                        group new { u, m } by new
                        {
                            u.Name,
                            Column1 = m.Name,
                            m.EmpGuid,
                            m.Sex,
                            m.TypeFlag,
                            m.ClassId,
                            m.zbdlBusinesscode
                        }
                            into g
                            orderby g.Key.zbdlBusinesscode
                            select new ManagerModel
                            {
                                ClassId = g.Key.ClassId,
                                corpName = g.Key.Name,
                                Name = g.Key.Column1,
                                EmpGuid = g.Key.EmpGuid,
                                Sex = (Byte?)g.Key.Sex,
                                TypeFlag = g.Key.TypeFlag,
                                TypeFlagName = g.Key.TypeFlag == "100" ? "项目主管" : g.Key.TypeFlag == "101" ? "项目经办人" : g.Key.TypeFlag == "103" ? "普通招标代理人员" : null,
                                zbdlBusinesscode = (g.Key.zbdlBusinesscode == "无" || g.Key.zbdlBusinesscode == null) ? "" : g.Key.zbdlBusinesscode
                            };

            if (managermodel != null)
            {
                if (managermodel.ClassId != null)
                {
                    query = query.Where(q => q.ClassId == managermodel.ClassId);
                }
                if (!string.IsNullOrEmpty(managermodel.TypeFlag))
                {
                    query = query.Where(q => q.TypeFlag == managermodel.TypeFlag);
                }
                if (!string.IsNullOrEmpty(managermodel.corpName))
                {
                    query = query.Where(q => q.corpName.Contains(managermodel.corpName));
                }
                if (!string.IsNullOrEmpty(managermodel.Name))
                {
                    query = query.Where(q => q.Name.Contains(managermodel.Name));
                }
            }

            count = query.ToList<ManagerModel>().Count;
            return query.ToList<ManagerModel>();
        }

        #endregion

    }


}
